Video in progress

Strong Middle 🧱 OOP and SOLID

How do you model order statuses and the transitions between them in OOP?

For a small, stable set of states, an enum with the allowed transitions and a single transitionTo method is enough. If behavior differs sharply per state, use the State pattern: each state is its own class and handles its own actions. The key point is that the transition rule lives in one place and isn't scattered across services as ifs.

📖 Answer

Scattered state logic is the problem itself:

if (order.getStatus() == NEW || order.getStatus() == PAID) order.setStatus(CANCELLED);

If a line like this sits in 6 services, then when you add a new SHIPPED state one of them will surely be forgotten.

A transition table with an enum:

public enum OrderStatus {
    NEW, PAID, SHIPPED, DELIVERED, CANCELLED;

    private static final Map<OrderStatus, Set<OrderStatus>> ALLOWED = Map.of(
        NEW, Set.of(PAID, CANCELLED),
        PAID, Set.of(SHIPPED, CANCELLED),
        SHIPPED, Set.of(DELIVERED),
        DELIVERED, Set.of(),
        CANCELLED, Set.of());

    public boolean canMoveTo(OrderStatus next) { return ALLOWED.get(this).contains(next); }
}

public class Order {
    private OrderStatus status = OrderStatus.NEW;
    public void cancel() { moveTo(OrderStatus.CANCELLED); }
    private void moveTo(OrderStatus next) {
        if (!status.canMoveTo(next)) throw new IllegalStateException(status + " -> " + next);
        status = next;
    }
}

There is no setStatus, only methods with meaning: pay(), ship(), cancel().

When you need the State pattern: when the same action works completely differently in each state (for example, cancel() just cancels in NEW, refunds the money in PAID and opens a return request in SHIPPED). Then you have an OrderState interface and classes like NewState and PaidState, each with its own behavior.

For very complex flows there are libraries like Spring Statemachine, but in most projects they are overkill: an enum and 30 lines of code are enough. If you need to keep the history of states, use a status_history table or domain events.