Alex Rivera | Logout

What is Cyclomatic Complexity?

Asked 2009-05-26T16:43:52.083
78

A term that I see every now and then is "Cyclomatic Complexity". Here on SO I saw some Questions about "how to calculate the CC of Language X" or "How do I do Y with the minimum amount of CC", but I'm not sure I really understand what it is.

On the NDepend Website, I saw an explanation that basically says "The number of decisions in a method. Each if, for, && etc. adds +1 to the CC "score"). Is that really it? If yes, why is this bad? I can see that one might want to keep the number of if-statements fairly low to keep the code easy to understand, but is this really everything to it?

Or is there some deeper concept to it?

Edit
Report

3 Answers

14
Cyclocmatic complexity = Number of decision points + 1

The decision points may be your conditional statements like if, if … else, switch , for loop, while loop etc.

The following chart describes the type of the application.

  • Cyclomatic Complexity lies 1 – 10  To be considered Normal applicatinon

  • Cyclomatic Complexity lies 11 – 20  Moderate application

  • Cyclomatic Complexity lies 21 – 50  Risky application

  • Cyclomatic Complexity lies more than 50  Unstable application

answered 2013-07-03T09:27:00.947
2

Each decision point in a routine (loop, switch, if, etc...) essentially boils down to an if statement equivalent. For each if you have 2 codepaths that can be taken. So with the 1st branch there's 2 code paths, with the second there are 4 possible paths, with the 3rd there are 8 and so on. There are at least 2**N code paths where N is the number of branches.

This makes it difficult to understand the behavior of code and to test it when N grows beyond some small number.

answered 2009-05-26T16:51:27.997
1

Consider the control flow graph of your function, with an additional edge running from the exit to the entrance. The cyclomatic complexity is the maximum number of cuts we can make without separating the graph into two pieces.

For example:

function F:
    if condition1:
       ...
    else:
       ...
    if condition2:
       ...
    else:
       ...

Control Flow Graph

Control Flow Graph

You can probably intuitively see why the linked graph has a cyclomatic complexity of 3.

answered 2009-05-26T16:52:44.623

Your Answer