Cyclomatic complexity of code is a quantitative measure created by Thomas McCabe to determine how many linearly independent paths a piece of code contains.
In software development, it is a widely used metric to indicate the complexity of a program. Mathematically, cyclomatic complexity (CC) is defined by the following formula:
M = E – N + 2P
To calculate it, the Control Flow Graph (CFG) is used. In this formula:
- E corresponds to the number of edges in the CFG,
- N is the number of nodes,
- P is the number of connected components.
In simple systems, functions, or methods, P is always equal to 1. However, we may want to measure the cyclomatic complexity of multiple systems at once—for example, measuring the complexity of all methods in a class. In that case, P will equal the number of methods being analyzed.
In the example above, we can identify 7 edges, 7 nodes, and only one component, which here is understood as a complete flow. Therefore, we have:
M = 7 – 7 + 2 × 1
M = 2
In this case, the cyclomatic complexity of this code block is 2, meaning there are two linearly independent paths:
- The path where B is greater than C,
- The path where B is not greater than C.
Having code that is too complex makes it harder to understand, identify, and fix bugs. It also complicates the execution of automated tests since more conditions need to be tested, which can lead to gaps in test coverage. Additionally, highly complex code requires greater cognitive load to understand—meaning it is harder to read because it contains very complex logic and multiple possible execution paths. As a result, such code is also more difficult to maintain and modify without introducing new bugs.
With that in mind, the benefits of having a metric that indicates the complexity of our application’s code become clear. By measuring cyclomatic complexity, we can identify code segments that need to be more modularized, improving quality, readability, and maintainability. Moreover, we can run automated tests more effectively, ensuring greater coverage of our codebase. This also helps identify new and/or potential bugs before they reach the production environment.