Cyclomatic Complexity

Cyclomatic complexity refers to the number of paths through a piece of code. If you want to impress people with fancy science talk, you can refer to this page at Carnegie-Mellon Software Institute. Suppose you had the following method on a class:

1   public bool IsSomeValue(bool foo, bool bar)
2   {
3     int i = 0;
4     if(foo)
5       i += 1;
6     if(bar)
7       i += -1;
8     return i += 2;
9   }

This would have a cyclomatic complexity of four because there are four paths through the code: in this case it is because of the possible combinations of the booleans, but it’s just a little example. We’ve all seen methods way more complex than this. What’s this metric for?

Well, the more paths through the code, the more difficult it is to debug and to test. The harder it is to debug and test, the higher likelihood of bugs. So measuring cyclomatic complexity is a way to find the methods that could potentially be the buggiest in a class. Note, it’s a potential for bugginess, no metric for software is absolute; computer science isn’t a science, you know. For example, suppose you had a giant enum of 20 values that you switched on. That method would have at least a cyclomatic complexity of 20, but is it necessarily that complex? Well, not really. However, if it had a cyclomatic complexity of 20 and there wasn’t a switch statement, alarms should be going off.

Measuring Cyclomatic Complexity is another tool in the toolbox to show you methods that might be troublesome and may require refactoring. This an especially good tool if you have a high code coverage of unit tests. If you’re around 95% percent, complex methods may not jump out at you because of every case is covered by a test. Just because it’s being tested doesn’t mean that the code is as good as it could be.

So what tools are there for measuring Cyclomatic Complexity? I’ve looked at a couple for C#:

  • CCMetrics – This one is good for measuring overall complexity of an assembly. It says right on the site that it ain’t ready for primetime, but it’s just a command line tool, so it’s really easy to get started and it generates an xml file for studying problems in detail. It works on the compiled assembly. The two measurements that I like is code reuse and complexity reuse. The price? Free.
  • devMetrics – This tool integrates into Visual Studio and works on the source code. I’ve only used the free edition, but with the one you pay for, you can make up your own metrics. The output is an html table containing stats on your solution. One of them is Cyclomatic Complexity including max complexity and average complexity for each class. It’s great for quickly identifying problem areas.

There are others that are included in larger toolsets, but for the money, the two above work well for me.