[SUMMARY] Clean Code Chapter 3: Functions (Robert C. Martin)

[SUMMARY] Clean Code Chapter 3: Functions (Robert C. Martin)

Small!

  • 2 to 6 lines long for each function to be transparently obvious.
  • Only 1 indent => everything in blocks (if, try …) should be a function call! 
  • Big functions are where classes hide => extract classes from functions! (A class is a group of functions that uses a common set a variable with 1 scope of responsibility)

Do One Thing

  • Functions should do one thing; they should do it well; they should do it only. 
  • Extract sub functions and classes until it’s not possible. 

The Stepdown Rule

  • Most abstract function at the top
  • Sub functions with a lower level of abstraction below it (It is possible in JS thanks to hoisting)

Switch Statements

Use Descriptive Names

  • A long descriptive name is better than a short enigmatic name.
  • Don’t be afraid to spend time choosing a name.
  • Hunting for a good name may result in a favorable restructuring of the code.

Function Arguments

  • Best: 0 (niladic) 
  • 2nd: 1 (monadic)  => function and argument should form a verb/noun pair.
  • 3rd: 2 (dyadic)
  • More than two should be avoided when possible

Reducing Arguments

  • Don’t use flag arguments in a function => split the function in two 
  • Use Objects: circle(x, y, radius) => circle(point, radius) 
  • More args => harder to test 

Have No Side Effects

  • Function should do one thing, but it also does other hidden things => bugs!

Command Query Separation (CQS) 

  • Query => returns the state on an object, no modification 
  • Command => modify the state, returns nothing

Exceptions over Error Codes

  • Returning error from command = violation of CQS. 
  • Error handling is one thing and functions should do one thing.

Don’t Repeat Yourself (DRY)

  • Eliminate duplication to have only one source of truth and one place to change.

Conclusion

Like writing a book where functions are verbs and classes are nouns, you don’t have clean code right away. You start with code that works as a first draft and refactor it to have a clean expressive code - TDD helps with that.  

For more details and analyses, I highly recommend reading the book!

The summary of the previous chapters are available as posts :)

#cleancode #tdd #cleanarchitecture #developpeur #fullstack

« Only 1 indent => everything in blocks (if, try …) should be a function call! » => This reduces our mental load so much!

Thank you for the summary, i will definitely read this book.

To view or add a comment, sign in

More articles by Ilias EL-MHAMDI

Others also viewed

Explore content categories