What problem are you trying to solve?
Simplify code and improve readability.
There are cases where while (true) {} loops make sense. But not all of them do.
In cases of while loop body starts with an if statement which decides to break the loop, the logic can be moved to the while loop condition.
What precondition(s) should be checked before applying this recipe?
Probably to start with:
- the
if is the first statement in the while loop
- the
if body has only break and nothing else
I am not sure whether this recipe should kick in if there are multiple break statements in the loop. Probably not. EDIT: why not?
Describe the situation before applying the recipe
int counter = 0;
while (true) {
if (counter >= 5) {
break;
}
System.out.println("Counter: " + counter);
counter++;
}
Describe the situation after applying the recipe
int counter = 0;
while (!(counter >= 5)) {
System.out.println("Counter: " + counter);
counter++;
}
Possibly the negation in the while condition could be simplified by delegating to other recipe.
OSS repro
What problem are you trying to solve?
Simplify code and improve readability.
There are cases where
while (true) {}loops make sense. But not all of them do.In cases of
whileloop body starts with anifstatement which decides to break the loop, the logic can be moved to the while loop condition.What precondition(s) should be checked before applying this recipe?
Probably to start with:
ifis the first statement in thewhileloopifbody has onlybreakand nothing elseI am not sure whether this recipe should kick in if there are multiple
breakstatements in the loop.Probably not.EDIT: why not?Describe the situation before applying the recipe
Describe the situation after applying the recipe
Possibly the negation in the while condition could be simplified by delegating to other recipe.
OSS repro