— 1 min read
To achieve high quality in your team's code, you should use tools like a static analyzer. These analyzers give you lots of metrics. One is the cyclomatic complexity. A very reduced definition is, that the more complex your methods are, the higher the cyclomatic complexity. A high complexity results from many different paths the program can take while running your code.
Many conditionals (
else) or branches in your code lead to higher complexity.
But why does the complexity matter? I want to give one quite simple reason, that entices a developer to reduce the complexity. It is not because the program is harder to reason about (that's also true!). Every possible path through your code increases the number of test cases the programmer has to write. It makes sense: If there are three possible paths, the program can take to reach the end of the method, you have to write at least three test cases to be sure everything works. Factor in that you probably will have different inputs to your methods, and the number of test cases increases quickly—because you have to test every path for every possible input. And it gets worse if your method depends on changing states or mutable data…
If you want to make your life easier when writing your tests, then decrease the complexity of your methods. Easy as that 😜