Cyclomatic complexity

Cyclomatic complexity is a software metric used to measure the complexity of code. Specifically, it directly measures the number of linearly independent paths through a method. Although not a rule, generally speaking the quality of the code can be inversely proportional to the cyclomatic complexity value, so the lower the score, the higher quality the code.

One of the best programs that I’ve found for quantifying this metric is SourceMonitor. This handy little freeware tool will give you the cyclomatic complexity of your classes as well as the individual methods within those classes so you can see exactly what requires attention in the event of a high score. It also gives other feedback too, such as number of lines of code and the number of methods per class among others.

Why should you care what cyclomatic complexity value your code gets? Well, apart from the warm glow you get inside from knowing that your code is well-written and elegant, there is a practical reason for it as well and that is the reduction of potential bugs. The more complex the code, the more difficult it is to keep track of what’s going on and the higher the risk of bugs creeping into your classes.

The accepted values for cyclomatic complexity are as follows:

  • 1 – 10: a simple program with a very low risk of bugs
  • 11 – 20: a more complex program with a moderate risk of bugs
  • 21-50: a very complex program with a high risk of bugs
  • > 50: untestable and obviously a number you want to stay well away from.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Translate »