Saturday, September 19, 2009

Product Metrics - Cyclomatic Complexity

Developed by Thomas J. McCabe Sr. in 1976. It is used to measure the complexity of a program. It directly measures the number of linearly independent paths through a program's source code. It is computed using the control flow graph of the program.

The simplest formula for calculating the Cyclomatic  Complexity is as follows

M = E – N + 2

 M = Cyclomatic Complexity
E = Number of edges in the control graph
N = Number of nodes in the control graph


 

Sample 1:
Simple If statement, the CC will be
M = 3 - 3 + 2 ==> 2 

Sample 2:
If-else statement, the CC will be
M = 4 - 4 +2 ==> 2

Sample 3:
Switch block, the CC will be
M = 6 - 5 + 2 ==> 3

VSTS 2008 has inbuilt product metrics measurement option for LOC, CC, coupling and maintainability index. SourceMonitor is another open source tool which helps to measure some of the the product metrics including CC.

Complexity definition:

Cyclomatic Complexity
Risk Evaluation
1 to 10
a simple program, without very much risk
11 to 20
a more complex program, moderate risk
21 to 50
a complex, high risk program
> 50
an un-testable program (very high risk)

1 comment:

  1. Raj there is a more simpler way of calculating Cyclomatic Complexity.

    Just count the number of decision boxes and add 1 to it.
    CC=No. of decision box+1

    ReplyDelete