while loop with an empty body
ID |
apex.correctness.empty_while_block |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Apex |
Rationale
A loop whose body does nothing either spins until the CPU governor limit kills the transaction, or does nothing at all - and which of the two it is depends on whether the condition can change without a body to change it. Neither is what the author intended. The shape usually appears when the body was emptied by a refactor, or when a while was written where a guard clause was meant.
The following code illustrates the pattern detected by this rule:
public class EmptyWhiles {
public void run(List<Account> accts) {
// FLAGGED: while loop with an empty body
while (!accts.isEmpty()) {
}
// FLAGGED: while loop with an empty body
while (accts.size() > 0) { }
while (!accts.isEmpty()) {
accts.remove(0);
}
}
}