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?
Use guard clauses: Return early for invalid or edge cases.
Extract methods: Move nested logic into separate methods with descriptive names.
Combine conditions: Merge related conditions with
&&or||operators.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
