Cyclomatic Complexity
Software Metrics are widely used in software developers. They are a standard of measure of a degree to which a software system or process possesses some property. There are many software metrics that are widely used but in this blog post, I am going to concentrate on one — Cyclomatic Complexity.
Cyclomatic complexity is a software metric, used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code. It is based on the idea that the higher this number the more complex the code. It was developed by Thomas J. McCabe, Sr. in 1976.
Calculation of Cyclomatic Complexity
Cyclomatic complexity is derived from the control flow graph of a program as follows:
Cyclomatic complexity (CC) = E — N + 2P
Where:
P = number of disconnected parts of the flow graph (e.g. a calling program and a subroutine)
E = number of edges (transfers of control)
N = number of nodes (sequential group of statements containing only one transfer of control)
In this example,
CC = number of edges — number of nodes + 2P
CC = 14–12 + (2*1)
CC = 4
Significane of the Cyclomatic Complexity
Measurement of McCabe’s cyclomatic complexity metric ensures that developers are sensitive to the fact that programs with high McCabe numbers (e.g. > 10) are likely to be difficult to understand and therefore have a higher probability of containing defects. Moreover, when multiple developers work on the same project, a lower CC indicates a higher probability of the developers collaborating more efficiently. The cyclomatic complexity number also indicates the number of test cases that would have to be written to execute all paths in a program.

The above figure shows the Cyclomatic complexities of different parts of the program. Such a figure gives developers an idea of which parts of the codebase need to be improved. If in such a figure most of the areas are red or black, then the codebase is in need of serious improvement.
