Skip to main content

Code reviews rule: Excessive nesting of conditional statements

Written by David Martin
Updated this week

Excessive nesting of conditional statements

Why is this an issue?

Deeply nested conditional statements (if/else chains) make code:

  • Hard to read: Readers must track multiple levels of conditions

  • Difficult to test: Each nesting level multiplies the number of test cases needed

  • Prone to bugs: Complex nesting increases the chance of logic errors

Examples

Example of incorrect code:

if (account != null) {
if (account.Type == 'Enterprise') {
if (account.AnnualRevenue > 1000000) {
if (account.Industry == 'Technology') {
// Deep nesting - hard to follow
}
}
}
}

Example of correct code using guard clauses:

if (account == null) return;
if (account.Type != 'Enterprise') return;
if (account.AnnualRevenue <= 1000000) return;
if (account.Industry != 'Technology') return;

// Main logic here - no nesting

How can I fix violations?

  1. Use guard clauses: Return early for invalid or edge cases.

  2. Extract methods: Move nested logic into separate methods with descriptive names.

  3. Combine conditions: Merge related conditions with && or || operators.

  4. Use polymorphism: Replace complex conditionals with strategy or state patterns.

Configuration options

You can configure the maximum allowed nesting depth for if statements. The default maximum depth is 3.

When should I disable this rule?

You may dismiss specific violations for inherently complex business logic where flattening would reduce clarity.

Resources

Did this answer your question?