Replace Control Flag with Break

Removes smells
Compare
Symptom
Human

A loop maintaining a boolean flag to decide when to stop — `let found = false; for (...) { if (!found && ...) { ...; found = true; } }`.

Agent

A loop maintaining a boolean flag to decide when to stop; the agent reasoning about termination must track the flag's state through every iteration.

Goal
Human

Loops that maintain a boolean to decide when to stop replace it with a direct `break`, `return`, or `continue`.

Agent

The exit happens at the moment it's decided via break/return/continue; the agent reads the loop's termination as a direct statement.

Before the refactoring

let found = false;
for (const p of people) {
if (!found && p.name === target) {
matched = p;
found = true;
}
}

After the refactoring

for (const p of people) {
if (p.name === target) {
matched = p;
break;
}
}
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure
Human

The exit condition is delayed and obscured; reasoning about when the loop terminates requires tracking the flag's state through every iteration; bugs hide where the flag isn't set when expected.

Agent

The agent must mentally simulate the flag's lifecycle across iterations; bugs hide where the flag isn't set when expected.

Tradeoff
Human

If the loop body is large, the break can hide the early-exit semantics — extract a function around the loop's body to keep the exit obvious.

Agent

If the loop body is large, the break point becomes hidden inside the body and the agent must scan to find termination; extract a function around the body to keep the exit obvious.

Relief
Human

The exit condition appears at the moment it's decided, not as a delayed effect of a flag check; the loop's intent becomes literal.

Agent

The agent reads termination as a direct statement at the point of decision; the loop's intent becomes literal.

Trap
Human

Replacing a flag with a break in a large loop body — the exit point becomes hidden inside the body, and the loop's termination semantics become harder to read than the original flag.

Agent

Replacing flags with breaks in large loop bodies buries the exit point — the agent must scan the body to find termination, which can be harder than tracking the flag.