← Writing

Java Early Return Pattern — Handle Failure Conditions Before Nested Logic

On this page

Returning the reason an order cannot be canceled near the start of the method lets you read the checks from top to bottom. An early return uses return to exit a method before reaching its end. A guard clause handles a condition that prevents execution from proceeding to the next step. Here, each guard clause immediately returns a reason to reject the cancellation. Java Language Specification §14.17

Replace nested if statements with guard clauses

canCancelBefore returns ALLOWED from the innermost block when the order exists, has been paid for, and has yet to ship. When a check fails, the method returns the corresponding reason at that level. canCancel checks the same three conditions from top to bottom and returns the first failure it finds. Both methods have three conditions, but the nesting depth and reading order change.

Take an order and check for null, lack of payment, and shipment in that order. The first true condition returns NOT_FOUND, NOT_PAID, or ALREADY_SHIPPED, respectively. If all three are false, return ALLOWED.

A false condition continues down the left side. Reaching ALLOWED requires passing all three guards.

Preserve the order of failure checks

Checking order == null first avoids calling order.status() or order.shipped() on a missing order. Keep the payment check before the shipment check. If inconsistent data marks an order as PENDING with shipped set to true, the original method returns NOT_PAID. Swapping the two checks would return ALREADY_SHIPPED, which can change the behavior of callers that map the result to an API error.

Verify both methods with five inputs

Save the code below as OrderCancellation.java and run java OrderCancellation.java with Java 21. For each input, main compares the two results individually against the same expected value and throws an AssertionError if either differs.

public class OrderCancellation {
    enum Status { PENDING, PAID }

    enum Result { NOT_FOUND, NOT_PAID, ALREADY_SHIPPED, ALLOWED }

    record Order(Status status, boolean shipped) {}

    static Result canCancelBefore(Order order) {
        if (order != null) {
            if (order.status() == Status.PAID) {
                if (!order.shipped()) {
                    return Result.ALLOWED;
                }
                return Result.ALREADY_SHIPPED;
            }
            return Result.NOT_PAID;
        }
        return Result.NOT_FOUND;
    }

    static Result canCancel(Order order) {
        if (order == null) {
            return Result.NOT_FOUND;
        }
        if (order.status() != Status.PAID) {
            return Result.NOT_PAID;
        }
        if (order.shipped()) {
            return Result.ALREADY_SHIPPED;
        }
        return Result.ALLOWED;
    }

    public static void main(String[] args) {
        check(null, Result.NOT_FOUND);
        check(new Order(Status.PENDING, false), Result.NOT_PAID);
        check(new Order(Status.PENDING, true), Result.NOT_PAID);
        check(new Order(Status.PAID, true), Result.ALREADY_SHIPPED);
        check(new Order(Status.PAID, false), Result.ALLOWED);
        System.out.println("Both methods passed all 5 cases.");
    }

    private static void check(Order order, Result expected) {
        Result before = canCancelBefore(order);
        Result after = canCancel(order);
        if (before != expected || after != expected) {
            throw new AssertionError(
                "%s: expected %s, before %s, after %s"
                    .formatted(order, expected, before, after)
            );
        }
    }
}
Order input Expected result
null NOT_FOUND
PENDING, false NOT_PAID
PENDING, true NOT_PAID
PAID, true ALREADY_SHIPPED
PAID, false ALLOWED

Both methods matched all five expected results on Zulu OpenJDK 21.0.1. The actual output was Both methods passed all 5 cases.

When guard clauses fit

Guard clauses work well for input validation, missing lookup results, and rejected state transitions when processing can stop at the first failure. Returning early from a method that collects all validation errors can leave later errors out of the result. If success and failure share an audit log, check whether moving a return creates a path that skips the log.

Discussion

View on GitHub ↗