6

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?

3 Answers3

2

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.

Jules
  • 17,880
  • 2
  • 38
  • 65
-1

The simplest solution to this question is to count the number of condition checks in the entire code and then add 1 to the result which will bring the cyclomatic complexity as output.

Solution Condition 1 :- if (this.isVerified) Condition 2 :- if (this.noOfB > 4)

So the total no of predicates or conditions is 2 and formula is V(G) = N(P) + 1 = 2 + 1 Hence answer is 3

-2

One thing that you're missing here that substantially increases the complexity of the function is that it's a member function that is mutating the state of the object. You seem to have modelled it as if they were just regular local variables.

DeadMG
  • 36,914