Deeply Nested If Statements
ID |
java.nested_if |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
Java |
Tags |
complexity, readability |
Description
Reports an if statement nested more deeply than the configured limit, counting the enclosing if statements within the same method, constructor or lambda.
An else if continuation does not add a level: it is the else branch of the previous if, a sibling of it rather than a child, so a long else if chain stays at depth 1.
Rationale
Each level of nesting multiplies the number of paths a reader has to hold in their head, and the conditions that reach a deeply buried statement are rarely visible from where it sits. The same shape makes the code hard to test: covering the innermost branch means satisfying every enclosing condition at once.
if (express) {
if (bulky) {
if (fragile) {
if (insured) {
if (weekend) { // depth 5 — what has to be true to get here?
return surcharge();
}
}
}
}
}
return 0;
Remediation
Invert the conditions and return early, so each requirement is stated once and the main path stays at the left margin. Where the conditions belong together, give them a name by extracting a method or combining them into a single predicate.
if (!express || !bulky || !fragile) {
return 0;
}
if (insured && weekend) {
return surcharge();
}
return 0;