#9. Keep functions short and cohesive

A function should have one specific purpose. And it should achieve its purpose by means of a cohesive structure.

A function can be structured in one of these ways:
  • A sequence of actions.
  • A condition.
  • A repetition of certain actions.
These control flow structures can be combined to form more sophisticated units. For example, a function may be a sequence of actions, with some of them being executed only under some conditions, and some other being loops. A certain degree of composition may be useful, but if you're not very strict, you'll soon find yourself writing 50-line functions which lack any structure.

Software scientists have long attempted to measure the complexity of code. Cyclomatic complexity measures the number of linearly independent paths through a program's source code. The higher cyclomatic complexity a function has, the harder it is to test.

If your function is a condition, you may need to test it in two different scenarios (paths): when the condition is true, and when it is false. If it contains four conditions, suddenly the scenarios become 2^4, that is, 16. If it is a combination of nested conditions with some loops spread out here and there, it will be a testing and maintenance nightmare. Some of these long and overly functions contain bugs ever since they begin to exist. Nobody has found them yet, because they are hidden in a path which requires five different conditions to be met. But they will appear, eventually.

Real life software problems are usually complex, but you should divide that compexity among different, simple software elements, each of them doing its job in an effective and easy to test way. The function is the smallest software element: you can't write unit tests for something smaller than a function. Complex "parts" of a potentially long function deserve to be in their own functions, with clearly defined semantics and which can be tested independently.


[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book has an interesting section about complexity in software, 34.1: "Conquer Complexity" (pages 837-839), inside its valuable chapter 34: "Themes in Software Craftmanship".


Popular posts from this blog

#13. Organize your code in classes

#11. Don't use syntactic overloading

#2. Make all type conversions explicit