
Next part of my notes from Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin.

“Functions should do one thing. They should do it well. They should do it only.”
Robert C. Martin
- Functions should be small.
It is much better to have many small functions with distinct responsibilities than a big one. It is easier to find your stuff when it is organized in drawers than put all together in one big box! Functions should be no longer than about 6 or so lines. Blocks within if, while etc.statements should be only one line long – a function call. The function should not be large enough to hold nested structures. The indent level should not be more than two. - Every function should do only one thing (see my post on SOLID principles: Single Responsibility Principle).
- The step down rule- code should be read from top to bottom.
Every function is followed by those at the next level of abstraction. A function that has several higher-level functions referring to it is placed after the last one. Otherwise it is placed directly underneath the function that refers to it.
“We like to put the private utilities called by a public function right after the public function itself. This follows the stepdown rule and helps the program read like a newspaper article.”
- One level of abstraction per function.
- Function should not have more than two arguments.
A function should have preferably no arguments but also one or two are okay. If you need many arguments, it is better to create a class and pass and object of this class. Arguments may mix levels of abstraction. You have to write tests that handle every permutation of the arguments. - Avoid creating functions with one flag argument.
That indicates that this function does two things- one when flag is true, the other when flag is false. Such a function should be split into two functions.
An output argument is one for which the argument instance itself is modified by the function. - Avoid output arguments.
An output argument itself is modified by the function. Output arguments are harder to understand than input arguments. - Avoid side effects as they break Single Responsibility Principle.
“Side effects are lies. Your function promises to do one thing, but it also does other hidden things that the name of the function does not imply.”
- Extract code from try and catch blocks to separate functions.
- Avoid repeating the same blocks of code.
- Separate commands from queries.
A command function changes the state of an object. A query returns something. A function should not do both.
References
Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin