tym
tym

Reputation: 73

Cyclomatic Complexity edges

So I'm trying to figure out if that blue line is in the right place, I know that I should have 9 edges but not sure if it's correct.

The code

public int getResult(int p1, int p2) {
int result = 0; // 1
if (p1 == 0) {  // 2
    result += 1; //3
} else {     
    result += 2; //4
}
if (p2 == 0) {   //5
    result += 3; //6
} else {
    result += 4; //7
}
    return result; //8 exit node
} 

so 8 nodes and it should have 9 edges, right? Did I do the right thing?

enter image description here

Upvotes: 0

Views: 166

Answers (2)

Mesut GUNES
Mesut GUNES

Reputation: 7401

According to wikipedia:

M = E − N + 2P, where

E = the number of edges of the graph. N = the number of nodes of the graph. P = the number of connected components.

so:

9 - 8 + 2*1 = 3

Upvotes: 0

Shweta Sharma
Shweta Sharma

Reputation: 161

Yes, the blue line is placed correctly because after the 3rd line, your program is going to jump to the 5th line. The easiest way to compute cyclomatic complexity without drawing any flow diagram is as follows:

  1. Count all the loops in the program for, while, do-while, if. Assign a value of 1 to each loop. Else should not be counted here.
  2. Assign a value of 1 to each switch case. Default case should not be counted here.
  3. Cyclomatic complexity = Total number of loops + 1 In your program, there are 2 if loops, so the cyclomatic complexity would be 3(2+1)

You can cross-check it with the standard formulae available as well which are as below: C = E-N+2 (9-8+2=3)

OR

C = Number of closed regions + 1 (2+1=3)

Upvotes: 1

Related Questions