Three levels of nested if statements
ID |
apex.maintainability.deeply_nested_if |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
Apex |
Rationale
At three levels the reader has to hold three live conditions to know why a statement runs, and every later edit has to re-establish them. In Apex this shape concentrates in trigger handlers, where the outer tests are usually context checks (Trigger.isInsert, a record type, a null guard) that could be guard clauses returning early, and the innermost body is the only code that matters. Deep nesting is also where a governor-limit-heavy call hides from review.
The following code illustrates the pattern detected by this rule:
public class NestedIfs {
public void handle(Account a, Boolean isInsert, Boolean isUpdate) {
// FLAGGED: Three levels of nested if statements
if (a != null) {
if (isInsert) {
if (a.Name != null) {
System.debug('deep');
}
}
}
}
public void guarded(Account a, Boolean isInsert) {
if (a == null) {
return;
}
if (isInsert && a.Name != null) {
System.debug('flat');
}
}
public void twoLevels(Account a, Boolean isInsert) {
if (a != null) {
if (isInsert) {
System.debug('two');
}
}
}
}