Cyclomatic Complexity
Cyclomatic complexity is a quantitative measure of the number of independent paths through a program's source code. It was developed by Thomas McCabe and is one of the most widely used software metrics.
Formula
V(G) = E - N + 2P
Where:
E = Number of edges in the control flow graph
N = Number of nodes in the control flow graph
P = Number of connected components (usually 1)
Simplified for methods:
V(G) = Number of decision points + 1
Complexity Calculation Examples
// V(G) = 1 (no decisions, just sequential code)
int add(int a, int b) {
return a + b;
}
// V(G) = 2 (one if statement = 2 paths)
int absoluteValue(int n) {
if (n < 0) {
return -n;
}
return n;
}
// V(G) = 4 (if + else if + else = 4 paths)
String getGrade(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
Complexity Thresholds
+---------------------------------------------------------+
| Complexity | Risk Level | Action Required |
+-------------+---------------+--------------------------+
| 1-10 | Low | Simple, low risk |
| 11-20 | Moderate | Consider refactoring |
| 21-50 | High | Refactor immediately |
| 50+ | Very High | Unmaintainable, redesign |
+-------------+---------------+--------------------------+
Reducing Cyclomatic Complexity
- Extract complex conditions into well-named boolean methods
- Replace conditionals with polymorphism when appropriate
- Use lookup tables or maps instead of long if/else chains
- Break large methods into smaller, focused methods
Key Takeaways
- Cyclomatic complexity measures the number of independent paths
- Keep complexity below 10 for maintainable code
- High complexity correlates with more defects
- Refactoring can reduce complexity without changing behavior