Cyclomatic Complexity (CC) is one of the software metrics that can be used to measure the level of the program’s complexity based on the number of paths that the program can take. This metric is one of the most useful ones that measure the number of decisions that are being taken within the program and it can also show the number of loops, conditions and function calls within the code. CC is a measure that tells developer how much effort is going to have to put in to test a given piece of code.
Cyclomatic Complexity is based on Graph Theory and the calculation is done with help of Control Flow Graphs, in these graphs:
The Cyclomatic Complexity can be calculated using the formula CC = E – N + 2P, where:
A high CC means that the code contains a lot of branches and, therefore, there is a high possibility of errors. It is easier to work with simple code than with complex code because the former is easier to read, modify, and debug. Therefore, this metric is valuable in several ways:
Although the Cyclomatic Complexity is higher in certain cases it may indicate the existence of problems, this doesn’t mean that complex code is always wrong. There are certain programs which inherently contain intricate decision making structures. However, this high complexity should make one to take some time and make sure that the complexity is required and that the code is well organized and documented.
In general, high Cyclomatic Complexity can lead to:
Cyclomatic Complexity is one of the most important software metrics that define the program’s complexity based on the number of control flow paths. It is a very helpful technique to find the code fragments that might be prone to issues and channel the code review, testing, and refactoring activities. On the downside, high complexity might mean more difficult and prone to errors code but on the other hand it is possible to enhance the quality of the software by reducing complexity of the structures and making sure that all possible defects have been tested.