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

Description

Reports a while loop whose body contains no statements.

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);
        }
    }
}

Remediation

Fill the body with the work the loop was meant to do, or delete the loop. If the loop was waiting for a condition to change, remember that Apex has no concurrency inside a transaction: nothing else can change it, so the wait cannot end.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved