Lift Break Into Loop Condition

ID

go.lift_break_into_loop_condition

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Go

Tags

CWE:1164, code-style, readability

Description

Reports a bare for loop whose first statement is an if cond { break }. The guard can be lifted into the loop header as for !cond { …​ }.

Rationale

A loop’s termination condition is easiest to understand when it is stated once, in the loop header. A bare for that immediately tests a condition and breaks hides that condition inside the body, forcing the reader to scan the loop to learn when it stops. Lifting the guard into the header — for !cond { …​ } — makes the loop self-describing and removes a level of nesting. The check fires only when the if cond { break } is the first statement of a bare for (no existing init, range or condition) and its body is exactly an unlabelled break.

for {
    if done() { // FLAW — lift into the condition
        break
    }
    work()
}

for !done() { // OK — condition stated up front
    work()
}

Remediation

Negate the guard condition and move it into the for header, deleting the if/break.