Video in progress

How do you simplify a method with lots of nested `if`s using guard clauses?

You check the error and edge cases at the start of the method and immediately return or throw. That way the main logic doesn't get pushed inward; it stays flat on the left and is easier to read.

📖 Answer

The "arrow" shaped code:

public void ship(Order order) {
    if (order != null) {
        if (order.isPaid()) {
            if (!order.getLines().isEmpty()) {
                if (order.getAddress() != null) {
                    courier.send(order);
                } else throw new IllegalStateException("manzil yo'q");
            }
        } else throw new IllegalStateException("to'lanmagan");
    }
}

You have to count to work out which else belongs to which if. And the empty-lines case passes through completely silently.

With guard clauses:

public void ship(Order order) {
    Objects.requireNonNull(order, "order");
    if (!order.isPaid())             throw new IllegalStateException("to'lanmagan");
    if (order.getLines().isEmpty())  return;
    if (order.getAddress() == null)  throw new IllegalStateException("manzil yo'q");

    courier.send(order);
}

Each condition is on its own line, and the main work comes last with no indentation.

The old rule that "a method should have only one return" is left over from the C days (it was for cleaning up resources). Java has try-with-resources and a GC, so returning early is fine.

The next step: if the guards pile up (5-6 of them) and they are about the object itself, move them into a method like order.ensureShippable().