Branch controlled by a literal condition
ID |
apex.correctness.useless_true_false_blocks |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Apex |
Description
Reports an if or a while whose condition is the literal true or false, so the branch is decided at compile time.
Rationale
if (true) runs unconditionally and if (false) never runs, which makes one of them a block of dead code that still has to be read, understood and maintained - and that no test can cover. The shape is what a temporary debugging edit leaves behind: a condition replaced by a literal to force a path, then committed. while (false) is the same mistake in a loop. while (true) is not reported: with a break it is an accepted idiom for a retry or a paging loop.
The following code illustrates the pattern detected by this rule:
public class LiteralConditions {
public void run(Boolean flag, List<Account> accts) {
// FLAGGED: Branch controlled by a literal condition
if (true) {
System.debug('always');
}
// FLAGGED: Branch controlled by a literal condition
if (false) {
System.debug('never');
}
// FLAGGED: Branch controlled by a literal condition
while (false) {
accts.clear();
}
if (flag) {
System.debug('conditional');
}
while (!accts.isEmpty()) {
accts.remove(0);
}
}
}