Cyclomatic Complexity: The Hidden Cost of Branching Logic
Cyclomatic Complexity, introduced by Thomas J. McCabe in 1976, quantifies the number of independent execution paths in code. A higher score indicates more complex, harder-to-understand, test, and maintain code, directly correlating with increased testing effort and a higher likelihood of defects.
The top 3
- Thomas McCabe's 1976 Origin of the Metric: Cyclomatic complexity was introduced by Thomas J. McCabe Sr. in his 1976 paper, 'A Complexity Measure,' to quantify code complexity and predict defects, moving beyond simple lines of code. It uses graph theory to count linearly independent execution paths.
- Top 3 Refactoring Patterns to Reduce Complexity: To lower cyclomatic complexity, break down complex functions into smaller, single-responsibility units, replace nested conditionals with design patterns like Strategy, and eliminate unnecessary branching or redundant code.
- Industry Standard Thresholds for Cyclomatic Complexity: NIST recommends a maximum cyclomatic complexity of 10 per function, a threshold widely adopted. Scores 1-5 are simple, 6-10 manageable, 11-20 complex and needing refactoring, and above 20 indicate very high risk and untestable code.
Sources
Open the full topic