L1l1th
L1l1th

Reputation: 1

Cyclomatic Complexity number - do I have to count every statement separately as node?

I came across different ways of calculating CCN (according to formula CCN = E-N+2P) One way was to count all the lines in the code separately and the other way is to count a few lines of code as one step; lets have the following example:

1 public class SumAndAverage {   
2
3   public static void main (String[] args) {
4       int sum = 0;            
5       double average = 0.0;   
6       String message = "";
7          
8       int num = Integer.parseInt(args[0]); 
9       
10      if ((num < 1) || (num > 100)) {  
11          message = "Invalid number entered.";  
12      } else {
13          for (int i = 1; i <= num; i++) {  
14              sum += i;  
15          }
16          average = (double) sum / num;  
17          message = "The sum is " + sum + " and the average is " + average;
18      }
19      System.out.println(message);  
20   }
21}

Counting every statement we'd get 12 - 11 + 2x 1 = 3

I was wondering if I "join" lines 4,5,6,8 and count them as one step and do the same with line 16 and 17, would that be correct too? The result would be the same as no of edges would also decrease: 8 - 7 + 2*1 = 3

Upvotes: 0

Views: 326

Answers (1)

KayDK
KayDK

Reputation: 134

The right way to calculate complexity is by considering blocks of code. A block of code is where there is no chance of dissecting the execution path. McCabe's paper mentions the below:

The tool, FLOW, was written in APL to input the source code from Fortran files on disk. FLOW would then break a Fortran job into distinct subroutines and analyze the control structure of each subroutine. It does this by breaking the Fortran subroutines into blocks that are delimited by statements that affect control flow: IF, GOTO ,referenced LABELS, DO, etc.

For other information on complexity, also read through Cyclomatic complexity as a Quality measure

Upvotes: 1

Related Questions