Cyclomatic Complexity

Cyclomatic complexity of a code section is the quantitative measure of the number of linearly independent paths in it.

Cyclomatic complexity (CYC) is a metric for software quality. It was developed by Thomas J. McCabe Sr. in 1976.

It can be used in two ways, to:

  • Limit code complexity.
  • Determine the number of test cases required.

It is computed using the Control Flow Graph of the program. The nodes in the graph indicate the smallest group of commands of a program, and a directed edge in it connects the two nodes

Calculate Cyclomatic Complexity:

M = E – N + 2P

where,

E = the number of edges in the control flow graph

N = the number of nodes in the control flow graph

P = the number of connected components

For example, if source code contains no control flow statement then its cyclomatic complexity will be 1 and source code contains a single path in it. Similarly, if the source code contains one if condition then cyclomatic complexity will be 2 because there will be two paths one for true and the other for false.

The graph shows 7 shapes(nodes), 7 lines(edges). Hence cyclomatic complexity is:

7-7+2 = 2.

Following table gives idea about complexity levels