Nested if whose outer branch holds nothing else
ID |
apex.maintainability.collapsible_if |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Complexity |
Language |
Apex |
Description
Reports an if whose body contains only another if, with neither of them carrying an else branch. The two conditions can be merged into one. The outermost pair of a chain three levels deep is left to the nesting rule, which already reports that shape.
Rationale
The outer if adds a level of indentation and a second decision point without expressing a second decision - both conditions have to hold for anything to happen. Flattening removes a branch, shortens the path a reader has to follow, and makes it obvious that the two tests belong together. In Apex it also keeps trigger and handler bodies, which nest quickly, within a depth a reviewer can hold in their head.
The following code illustrates the pattern detected by this rule:
public class CollapsibleIf {
public void bothSet(Boolean a, Boolean b) {
// FLAGGED: Nested if whose outer branch holds nothing else
if (a) {
if (b) {
System.debug('both');
}
}
}
public void threeDeep(Boolean a, Boolean b, Boolean c) {
if (a) {
// FLAGGED: Nested if whose outer branch holds nothing else
if (b) {
if (c) {
System.debug('all three');
}
}
}
}
public void merged(Boolean a, Boolean b) {
if (a && b) {
System.debug('both');
}
}
public void outerDoesMore(Boolean a, Boolean b) {
if (a) {
System.debug('outer');
if (b) {
System.debug('both');
}
}
}
public void innerHasElse(Boolean a, Boolean b) {
if (a) {
if (b) {
System.debug('both');
} else {
System.debug('only a');
}
}
}
public void outerHasElse(Boolean a, Boolean b) {
if (a) {
if (b) {
System.debug('both');
}
} else {
System.debug('neither');
}
}
}