Skip to content

Recipe to amend while true with conditions found in conditional statements in the body #610

@greg-at-moderne

Description

@greg-at-moderne

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions