Cyclomatic Complexity
- Cyclomatic complexity is a software metric (measurement), It was developed by Thomas J. McCabe, Sr. in 1976 and used to indicate the complexity of a program.
- It is quantitative measure of the number of linearly independent paths through a program’s source code.
- Cyclomatic complexity is computed using the control flow graph of the program: the nodes of the graph correspond to indivisible groups of commands of a program, and a directed edge connects two nodes if the second command might be executed immediately after the first command.
How Cyclomatic complexity is calculated
- Cyclomatic complexity may also be applied to individual functions, modules, methods or classes within a program.
- The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code. For instance, if the source code contained no decision points such as IF statements or FOR loops, the complexity would be 1, since there is only a single path through the code. If the code had a single IF statement containing a single condition there would be two paths through the code, one path where the IF statement is evaluated as TRUE and one path where the IF statement is evaluated as FALSE.
- Mathematically, the Cyclomatic complexity of a structured program is defined with reference to a directed graph containing the basic blocks of the program, with an edge between two basic blocks if control may pass from the first to the second (the control flow graph of the program).
- The complexity is then defined as:
$$M = E − N + P$$
Where
M = Cyclomatic complexity
E = the number of edges of the graph
N = the number of nodes of the graph
P = the number of connected components