Concept:
Cyclomatic complexity is a software metric developed by Thomas J. McCabe in 1976. It is used to indicate the complexity of a program by measuring the number of linearly independent paths through a program's source code. A "linearly independent path" is a path through the code that introduces at least one new edge (link) not contained in any other path.
Step 1: Understanding the Control Flow Graph (CFG).
To calculate this metric, the code is represented as a directed graph where:
• Nodes: Represent the smallest units of commands or executable statements.
• Edges: Represent the flow of control between these statements.
If the code has many decision points (if-else, switches, loops), the graph becomes more complex, and the number of paths increases.
Step 2: The Calculation Formula.
The formula for Cyclomatic Complexity $V(G)$ is:
\[ V(G) = E - N + 2P \]
Where:
• $E$ = Number of edges in the graph.
• $N$ = Number of nodes in the graph.
• $P$ = Number of connected components (usually 1 for a single module).
Alternatively, it can be calculated as: $\text{Number of Predicate Nodes} + 1$.
Step 3: Significance of the Metric.
A higher cyclomatic complexity indicates a higher probability of errors and makes the code harder to test. Specifically, the complexity value tells a tester exactly how many test cases are required to achieve "Basis Path Coverage"—ensuring that every single unique path through the code is executed at least once.