Cyclomatic Complexity
A quantitative measure of the number of linearly independent paths through a program's source code, indicating its structural complexity.
Also known as: McCabe Complexity, McCabe's Cyclomatic Number
Category: Software Development
Tags: software-engineering, metrics, quality, complexity, code-analysis
Explanation
Cyclomatic Complexity is a software metric developed by Thomas J. McCabe in 1976 that measures the structural complexity of code by counting the number of linearly independent paths through a program's control flow graph.
How it's calculated:
For a control flow graph with E edges, N nodes, and P connected components:
**M = E - N + 2P**
In practice, it equals the number of decision points (if, else, while, for, case, catch, &&, ||) plus one.
Complexity thresholds (commonly used):
- **1-10** - Simple, low risk, easy to test
- **11-20** - Moderate complexity, manageable
- **21-50** - Complex, difficult to test and maintain
- **51+** - Untestable, very high risk, should be refactored
Why it matters:
1. **Testability** - Cyclomatic complexity equals the minimum number of test cases needed for full branch coverage
2. **Maintainability** - Higher complexity correlates with more bugs and harder comprehension
3. **Code review focus** - Helps reviewers identify the riskiest code sections
4. **Refactoring signal** - High complexity is a clear indicator that a function should be broken down
How to reduce complexity:
- Extract complex conditional logic into well-named functions
- Replace nested conditionals with guard clauses or early returns
- Use polymorphism instead of long switch/if-else chains
- Apply the Strategy or State design pattern
- Break large functions into smaller, focused ones
Tools that measure it: ESLint (complexity rule), SonarQube, CodeClimate, Radon (Python), PMD (Java), Lizard (multi-language).
Cyclomatic complexity is most useful as a relative metric and warning signal rather than an absolute quality measure. It works best combined with other metrics like code coverage and cognitive complexity.
Related Concepts
← Back to all concepts