Visitar URL original
Recipe to prefer early return when handling some non-default code paths · Issue #609 · openrewrite/rewrite-static-analysis · GitHub
Skip to content

Recipe to prefer early return when handling some non-default code paths #609

Open

Description

@greg-at-moderne

What problem are you trying to solve?

Improve code readability in cases like a method declaration with one big if statement. One branch would contain a lot of logic, and the other branch would have a return and maybe one or two statements.
Such cases could be refactored to have the logic for non-default case at the top with an early return, and the rest of the logic in the top-level method body.

What precondition(s) should be checked before applying this recipe?

Some heuristics can be applied on when to apply the change. Finger in the air something like:

  • at least 5 statements in the "default" branch
  • at most 2 statements in the "non-default" branch.

Describe the situation before applying the recipe

public void processOrder(Order order) {
    if (order != null && order.isValid() && !order.isCancelled()) {
        // Main logic
        System.out.println("Processing order: " + order.getId());

        calculateTotals(order);
        applyDiscounts(order);
        updateInventory(order);
        sendConfirmationEmail(order);
        logOrderProcessed(order);
    } else {
        // Minimal branch
        System.out.println("Order is invalid or cancelled. Skipping processing.");
        return;
    }
}

Describe the situation after applying the recipe

public void processOrder(Order order) {
    if (order == null || !order.isValid() || order.isCancelled()) {
        System.out.println("Order is invalid or cancelled. Skipping processing.");
        return;
    }

    // Main logic
    System.out.println("Processing order: " + order.getId());

    calculateTotals(order);
    applyDiscounts(order);
    updateInventory(order);
    sendConfirmationEmail(order);
    logOrderProcessed(order);
}

Activity

  1. moved this to Recipes Wanted in OpenRewriteon Jun 30, 2025
  2. sahanarameshh commented on Jul 1, 2025

    @sahanarameshh

    Could I be assigned to this please?

  3. timtebeek commented on Jul 1, 2025

    @timtebeek
    Member

    Hi @sahanarameshh ! Thanks for you're interest to help out. We assign issues as soon as we see a draft PR with tests. Feel free to tag me as soon as you open one. Looking forward to it!

  4. removed their assignment
    on May 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    • Status
      Recipes Wanted

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions