Iris Classon
Iris Classon - In Love with Code

(Not so) Stupid Question 284-287: What is cyclomatic complexity, how do you calculate it and what does the score mean?

The other night I was reading a book on microservices (I’ll post a review later) and there was a part in book that mentions cyclomatic complexity. I’ll admit right now that I didn’t know what that was. I could make some good guesses, but that was about it. So let’s see if I got this one right.

Simplified cycliomatic complexity is a way to measure the complexity of a function/method/module based on the number of independent paths it has.

How many times would you need to execute that function to have walked through all the different paths, be that through loops, if elses or other type of branching?

The score indicated the complexity of the module and is often used as an indicator for maintainability and testability (more specific, how many test cases do we need to cover all branches?), although it can be calculated in different ways (to be covered in detail at a later point) and opinions are divided in regards to how useful it is.

M = E - N + P

Sometimes simplified to:

M = EN + 2

E : Edges are lines (also called vertices or arcs)

P: Predicates are decisions with two possible paths out

N: Nodes decision points (number of conditional statements - if,for,while etc.)

Here is an example:

// Yes, this is not a real method. I couldn’t come up with anything better in the moment

         public static bool ContainsGesture(int[] readings, int threshold)
       {
           foreach (var reading in readings)
           {
               if (reading > threshold)
               {
                   Console.WriteLine("Contains");
                   return true;
               }
           }
           return false;
       }

If I calculated right it has a cyclomatic complexity of 3 as it has 5 edges, four nodes and two predicates. Analyzing the method in Visual Studio does indeed show 3, but the ReSharper plugin calculates 4. And that’s the thing, there are different ways of calculating – so although an indicator it probably should be a hard rule.

cyclomatic complexity visual studio

 

[caption id=“attachment_31272” align=“aligncenter” width=“695”] cyclomatic complexity resharper I set the threshold to ‘2’ just to demo the plugin :)[/caption]

Anyway, 3 or 4 isn’t high. So what exactly is a high score? Going by the handbook for Carnegiege University in regards to software development ( and they use thie first calculation method I mentioned):

 

Cyclomatic Complexity Risk Evaluation

1-10 a simple program, without much risk

11-20 more complex, moderate risk

21-50 complex, high risk program

50 untestable program (very high risk)

PDF, page 155

 

But when is this useful to us, what can we do with it? The handbook suggests:

  • Code development analysis (inherent risk as code is being written)

  • Change risk in maintenance (calculate diff in CC after change allowing for strategies to minimize CC and correlated risk)

  • Test planning (indicator for number of test cases needed)

  • Reengineering (identify areas that need attention)

 

Do you use CC metrics, why/why not?

Comments

Leave a comment below, or by email.
Sean Killeen
1/23/2016 10:51:55 AM
Great post! I think cyclomatic complexity is one of the best indicators I have when looking at a project I've inherited with legacy code. It can indicate code that is violating the Single Responsibility Principle by trying to do too much, or code that can be better expressed (e.g. could that nest of if statements be better expressed as some human readable methods?) In a project without test coverage, the methods with the highest cyclomatic complexity are where I like to start pulling things out and picking them apart for tests. In some cases, I can extract whole classes and greatly simplify the structure. 

Glad to see you blogging about it because I think developers often overlook these metrics that can be so helpful in driving better structure/design/testability in our code. This could be the start of a great post series! :) 
Yawar
1/24/2016 12:43:52 AM
Interesting. What happens to the cyclomatic complexity if you express that method differently, e.g. in a functional paradigm like


using System.Linq;

class Program {
  public static bool ContainsGesture(int[] readings, int threshold) {
    return readings.Any(r => r > threshold);
  }
}


? 
Leif Larsen
1/24/2016 1:25:08 AM
I don't use CC today, mostly because I didn't know what it was. It does seem like good metrics to use, even though I'm a bit scared to think about the score the code base I work on daily would get..! 

On the scale from Carnegiege University, do you know what an average application scores? I realize that it varies a lot, but it would be interesting to know if there's been done any studies into it. 
Kevin Avignon
1/24/2016 12:10:12 PM
I use it in my personal projects as a metric to after writing my code and using unit tests to make sure the code won't break in any edge cases, to see if I need to refactor my code. Then afterwards, it becomes a mission of balancing refactoring and code clarity. I mean yes, refactoring is good, but not to the extent of making multiple methods to do replace the one of 12-20 lines, etc etc. 
In a large scale system, it depends. I don't know if you familiar with the Roslyn API? In one of my internships, my company used code analysis to make sure the file did not have over 80. Usually, it gets fairly easy for industry code to get over 50 CC. The trick is to make sure not go overboard and maybe think a bit about your code design and make some redefinition before going too deep. 
Andrew
1/25/2016 3:12:59 AM
Since there's no stupid questions here...

I still don't get it

Can you point out the E, P and N in your example explicitly? 
JuanKy
1/25/2016 1:08:58 PM
I'm been facing a cyclomatic complexity problem recently and it can be actually tricky to tackle certain methods.

Regarding to the article, straight, simple and as clear as usual! 
David
1/25/2016 4:38:01 PM
We use Cyclomatic Complexity scores only as a broad guideline.  I suspect most people will do this, if they use them at all.  We choose to look at the areas of code with the higher scores and then decide whether we can safely perform refactoring on that code.  Sometimes it's just not possible due to the legacy nature of the code that has little or no unit test coverage.  We don't have absolute rules as we trust our own judgement to choose what we can safely leave alone and what we can reliably re-engineer without breaking anything.

As a more general point, we do take an interest in the results from code analysis tools like FxCop, Visual Studio and ReSharper.  But we use the Pirates of The Caribbean approach when looking at the reports:   "... the code is more what you'd call "guidelines" than actual rules". 
Ben
1/26/2016 3:10:45 PM
Yes! I used them a lot at a previous job to support my case as to why some software I was being asked to support was close to impossible to support. I had been arguing the software was very hard to modify to which the response was "All developers say that". I asked if they would accept cyclomatic complexity as a measure as to how hard it was. The higher ups agreed and I went off to run things against a few of the applications that were particularly painful.

The worst method I found had a cyclomatic complexity score of 2700. I then showed a score of a well written project where the worst method had a score of 7 and they quickly came around to my way of thinking.

I also tend to use cyclomatic complexity as the first thing I run on any new code so I can quickly see where I may run into issues or where the majority of the code lies.

A very useful tool. 
Gary Hammett
1/28/2016 7:34:01 AM
Thanks for posting Iris,

I was not aware of Cyclomatic Complexity. But I think this is one of those very useful add-on's for Resharper.

I will definitely be using this in future. 
Rick
2/19/2016 7:44:42 AM
I haven't actually tried this using Visual Studio or Resharper, didn't really even realize the options were there. Learn something new every day. :) 

I can say I've definitely come across this in software development, but can't say I've paid as much attention to it as I probably should. Nice article. 
Alexander
2/25/2016 2:36:07 AM
Thanks for this post. I never used CC metrics before but you made me curious about it. 


Last modified on 2016-01-23

comments powered by Disqus