McCabe Cyclomatic Complexity

Cyclomatic complexity is a measure of a module's structural complexity. Studies show a correlation between a program's Cyclomatic Complexity and its maintainability and testability, implying that with files of higher complexity there is a higher probability of errors when fixing, enhancing, or refactoring source code.

The selected threshold is based on categories established by the Software Engineering Institute, as follows:

Cyclomatic Complexity Risk Evaluation...
1-10 A simple module without much risk
11-20 A more complex module with moderate risk
21-50 A complex module of high risk
51 and greater An untestable program of very high risk

Aggregation is affected by the selected structure, as defined in the selected model, and the scope, as defined by the structure preset.

Cyclomatic complexity is calculated as follows:

Cyclomatic Complexity = ( 1 + ifs + loops + cases ) where:

  • ifs is the number of IF operators in the function,
  • loops is the number of loops in the function,
  • cases is the number of switch branches in the function (without default), and

Here is the pseudo code of a simple program and the Cyclomatic Complexity metric for it.

Function
  While
    If
    Else
    Endif
  Endwhile
End Function 

Since there is one "if" and one "loop" operator, we can calculate the Cyclomatic Complexity metric as 1+1+1=3.