How to calculate Cyclomatic Complexity exactly

code metricscyclomatic-complexity

My question is more about the transformation from programming code to control flow graph.

Say, I have a piece of code:

public class Contractor
{
    // other member fields... 
    private bool isVerified;
    private int noOfA;
    private int noOfB;

    // other member methods... 
    public int GetNumberOfDependents()
    {
        this.noOfB = this.noOfA;

        if (this.isVerified)
        {
            this.noOfB++;
        }

        if (this.noOfB > 4)
        {
            this.noOfB = 4;
        }

        return this.noOfB;
    }
}

I drew a flow diagram as below:

enter image description here

And please note that I didn't draw a node for the condition expression of IF statement, because I dont think it is a 'command'.

According to the Wikipedia page about CC, the definition of node is:

the nodes of the graph correspond to indivisible groups of commands of
a program

And the formula is:

M = E − N + 2P

So I got its CC value as 4.

However, according to the description in this link, I got its CC value as 3.

There is a discrepancy here.

Moreover, according to David Tonhofer's answer to the question “Understanding Cyclomatic Complexity” on Programmers.SE, the formula in should be:

v(G) = e – v + p

That answer is not acknowledged by anyone, my question is: is my diagram correct?

Best Answer

Your flow diagram can be simplified as:

[this.noOfB = this.noOfA;]
   |           \
   |            \
   |           [noOfB++]
   |            /
   |           /
[-----------------]
   |           \
   |            \
   |           [noOfB = 4]
   |            /
   |           /
[-----------------]

This gives 5 nodes, 6 edges, and 1 connected component => M = 6 - 5 + 2*1 = 3. Generally speaking, cyclomatic complexity is usually calculated using control flow graphs that only have at most two edges leaving each node.

Related Topic