rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

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

Open greg-at-moderne opened this issue 6 months ago • 2 comments

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);
}

greg-at-moderne avatar Jun 30 '25 09:06 greg-at-moderne

Could I be assigned to this please?

sahanarameshh avatar Jul 01 '25 16:07 sahanarameshh

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!

timtebeek avatar Jul 01 '25 17:07 timtebeek