Cyclomatic complexity is a metric used to assess the complexity of a program's code or software module. It measures the number of independent execution paths within a program, based on its control flow structure. Developed by Thomas J. McCabe, this metric helps evaluate a program’s testability, maintainability, and susceptibility to errors.
Cyclomatic complexity V(G)V(G) is calculated using the control flow graph of a program. This graph consists of nodes (representing statements or blocks) and edges (representing control flow paths between blocks). The formula is:
V(G)=E−N+2PV(G) = E - N + 2P
In practice, a simplified calculation is often used by counting the number of branching points (such as If, While, or For loops).
Cyclomatic complexity indicates the minimum number of test cases needed to cover each path in a program once. A higher cyclomatic complexity suggests a more complex and potentially error-prone codebase.
By measuring cyclomatic complexity, developers can identify potential maintenance issues early and target specific parts of the code for simplification and refactoring.