Clean functions

Aaron Wang

What are functions

  • input => compute => output
  • Why?
    • Decompose a larger concept
    • Reuse code
  • First line of organization in any program

Should be Small

  • Long functions are hard to read and maintain
  • How small?
    • Under 30 lines is the best, 50 lines at most
    • No more than 3 indentation levels
  • Ways to make them small:
    • Split
    • Add extra abstract layers

SHOULD DO ONLY ONE Thing

  • Is it trying to do a lot?
  • Can it be split?
  • Does it involve multiple abstract layers? 

use polymorphism

  • Avoid repetitive if/else, switch
  • Bury if/else, switch in factory

FUnction arguments

  • The fewer, the better
  • Avoid flag arguments if possible
  • Use argument objects

Avoid side effects

  • In programming, nobody likes surprises
  • Don't do more than its name states

use exception instead of error code

DON"T repeat yourself

return early

  • Reduce netsting

HOw

  • Design, 40%
  • Refactor, 60%

Examples

  • https://gist.github.com/inetfuture/61a40d1cf5ec9b623afe7ab95b201191

THanks!

Clean Functions

By Aaron Wang

Clean Functions

  • 1,086