Chapter 3. Write Simple Units of Code

Each problem has smaller problems inside.

Martin Fowler

Guideline:

  • Limit the number of branch points per unit to 4.

  • Do this by splitting complex units into simpler ones and avoiding complex units altogether.

  • This improves maintainability because keeping the number of branch points low makes units easier to modify and test.

Complexity is an often disputed quality characteristic. Code that appears complex to an outsider or novice developer can appear straightforward to a developer that is intimately familiar with it. To a certain extent, what is “complex” is in the eye of the beholder. There is, however, a point where code becomes so complex that modifying it becomes extremely risky and very time-consuming task, let alone testing the modifications afterward. To keep code maintainable, we must put a limit on complexity. Another reason to measure complexity is knowing the minimum number of tests we need to be sufficiently certain that the system acts predictably. Before we can define such a code complexity limit, we must be able to measure complexity.

A common way to objectively assess complexity is to count the number of possible paths through a piece of code. The idea is that the more paths can be distinguished, the more complex a piece of code is. We can determine the number of paths unambiguously by counting the number of branch points. A branch point is a statement where execution can take more than one direction depending on a ...

Get Building Maintainable Software, Java Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.