Skip to content

Latest commit

Β 

History

History
88 lines (69 loc) Β· 1.55 KB

File metadata and controls

88 lines (69 loc) Β· 1.55 KB

prefer-while-loop-condition

πŸ“ Prefer putting the condition in the while statement.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§ This rule is automatically fixable by the --fix CLI option.

When a constant infinite loop immediately checks a condition and breaks, the loop condition is split across two places. Put the condition in the while statement so the loop's continuation condition is visible where readers expect it.

The rule only reports simple top-of-loop guards in while (true), for (;;), for (; true;), and do ... while (true) loops. Loops with labels, additional break statements targeting the same loop, or comments around the removable guard or loop syntax are ignored.

Examples

// ❌
while (true) {
	if (!hasMore()) {
		break;
	}

	processNext();
}
// βœ…
while (hasMore()) {
	processNext();
}
// ❌
do {
	if (!hasMore()) {
		break;
	}

	processNext();
} while (true);
// βœ…
while (hasMore()) {
	processNext();
}
// ❌
while (true) {
	if (done) {
		break;
	}

	processNext();
}
// βœ…
while (!done) {
	processNext();
}
// ❌
for (;;) {
	if (!hasMore()) {
		break;
	}

	processNext();
}
// βœ…
while (hasMore()) {
	processNext();
}