Skip to main content

Code reviews rule: Excessive code complexity

Written by David Martin
Updated this week

Excessive code complexity

Why is this an issue?

Cyclomatic complexity measures the number of independent execution paths through a piece of code. Complex code is:

  • Hard to test: More paths mean more test cases needed for full coverage.

  • Hard to understand: Developers struggle to follow complex logic.

  • Prone to bugs: Complex code is more likely to contain errors.

  • Difficult to maintain: Changes risk unintended side effects.

Examples

Example of incorrect code (deeply nested conditions):

public String getDiscount(Account acc) {
if (acc.Type == 'Enterprise') {
if (acc.AnnualRevenue > 1000000) {
if (acc.Years_As_Customer__c > 5) {
return '25%';
} else {
return '15%';
}
} else {
return '10%';
}
} else {
return '0%';
}
}

Example of correct code (simplified with early returns):

public String getDiscount(Account acc) {
if (acc.Type != 'Enterprise') {
return '0%';
}
if (acc.AnnualRevenue <= 1000000) {
return '10%';
}
if (acc.Years_As_Customer__c > 5) {
return '25%';
}
return '15%';
}

How can I fix violations?

Reduce complexity by refactoring.

  • Break large methods into smaller methods, each with a single purpose.

  • Split complex conditions into multiple well-named variables.

  • Use early returns to reduce nesting (the "Arrow anti-pattern").

  • Use strategy or state patterns instead of complex if/else chains.

When should I disable this rule?

You may dismiss specific violations for methods that inherently require complex logic, such as parsers or state machines, where the complexity is justified and well-documented.

Resources

Did this answer your question?