The functions chapter of Robert C. Martin’s Clean Code causes no great epiphany, but it is a good review. Some of the interesting points include:
- Small: Obviously, functions should be small. Ideally, they should be small enough that you can see the entire thing on one screen.
- Blocks and Indenting: It is rare to see somone not use indenting for blocks. I could care less where the curly brace goes, but I generally don’t like taking up extra vertical space with the curly brace on its own line.
- Do One Thing: If your function only does one thing, it will be small.
- One Level of Abstraction per Function: A good way to break up large functions keep code together that is at the same level abstraction. Move the lowest level of abstract out first.
- Reading Code from Top to Bottom: People read from top to bottom, so organize the functions so that they make the most sense read from top to bottom. The highest level of abstraction should be at the top.
- Switch Statements: Switch statements might be a sign that you should use inheritance to solve the problem
- Function Argument: Generally, the idea is that the fewer the arguments, the better. If there are more than one or two arguments, it probably should be done some other way. Flag arguments can easily be avoided.
- Command Query Separation: Functions should either do something or answer something, but not both.