Donald Barre
Donald A. Barre
Cyclomatic Complexity
When I bring up the topic of cyclomatic complexity, I find that most developers do not know what it is. Cyclomatic complexity was introduced by Thomas J. McCabe, Sr. in 1976. Very simply, it is a metric for measuring how complex a piece of code is. While it can be used for classes, I have always tended to use it for functions.
When we compute the cyclomatic complexity of a function, we get a numeric score from 1 to N. The score represents the risk. The higher the score, the greater the risk. The risks include bugs, unmaintainable code, and/or code that is hard to test. McCabe put forth the following:
Score Range Risk
1 - 10 Simple function, little risk
11 - 20 More complex function, moderate risk
21 - 50 Complex function, high risk
50+ Untestable code, very high risk
For a real life story, I once worked with a Staff Software Engineer who had written an 800+ line function. When I saw it, I decided to compute its cyclomatic complexity score. If my memory serves me, it had a score of 124. That's in the stratosphere. Not long after I told him about cyclomatic complexity and the score of 124, he found a bug in his function.
Computing cyclomatic complexity by hand is not trivial when dealing with a complex function. I recommend using a static analyzer. One popular tool is SonarQube, but there are others.
Cyclomatic complexity pairs well with my post Keep It Small. Functions with lots of lines of code are more likely to have a higher risk score.
Lastly, if you want to learn more about how cyclomatic complexity is computed, here's a good article, but there are also others that you can find with a simple search.
© Donald A. Barre. All rights reserved.