Tech Interview RoomStudy guides

Java 21

Java 21: Model an order lifecycle as a state machine. Compare string states, polymorphic states and pattern matching on (state, event) pairs.

Advanced · 2 min read · Lesson 4 of 8 in Java 21

Problem

An order moves through New → Placed → Paid → Shipped, and can be Cancelled before shipping. Events: PlaceOrder(total), Pay(amount), Ship(trackingId), Cancel(reason). Payment must match the order total. Invalid transitions must be rejected. This is a common senior-level design question; Java 21 makes it very concise.

Approach 1: String status with if/else (feasible, error-prone)

Typos compile, invalid combinations are easy to forget, and the data for each state (total, tracking id) lives in nullable fields.

java
class OrderStrings {
    String status = "NEW";
    long total;
    String tracking;

    void apply(String event, String arg) {
        if (status.equals("NEW") && event.equals("PLACE")) { total = Long.parseLong(arg); status = "PLACED"; }
        else if (status.equals("PLACED") && event.equals("PAY") && Long.parseLong(arg) == total) status = "PAID";
        else if (status.equals("PAID") && event.equals("SHIP")) { tracking = arg; status = "SHIPPED"; }
        else if ((status.equals("PLACED") || status.equals("PAID")) && event.equals("CANCEL")) status = "CANCELLED";
        else throw new IllegalStateException(event + " not allowed in " + status);
    }
}

Approach 2: Enum states with a transition method (Java 8, the "State pattern")

Type-safe states, but the per-state data still needs nullable fields, and events are loosely typed.

java
enum Status {
    NEW, PLACED, PAID, SHIPPED, CANCELLED;

    Status on(String event) {
        return switch (this) {
            case NEW -> event.equals("PLACE") ? PLACED : fail(event);
            case PLACED -> event.equals("PAY") ? PAID : event.equals("CANCEL") ? CANCELLED : fail(event);
            case PAID -> event.equals("SHIP") ? SHIPPED : event.equals("CANCEL") ? CANCELLED : fail(event);
            case SHIPPED, CANCELLED -> fail(event);
        };
    }
    private Status fail(String event) { throw new IllegalStateException(event + " not allowed in " + this); }
}

Approach 3: Sealed states and events as records + one pattern switch over the pair (Java 21)

Each state carries exactly the data it has (Paid has a total, Shipped has a tracking id), events carry their payloads, and every transition is one readable line. Guards (when) express business rules. The default catches invalid combinations explicitly.

java
sealed interface OrderState permits NewOrder, Placed, Paid, Shipped, Cancelled {}
record NewOrder() implements OrderState {}
record Placed(long totalPaise) implements OrderState {}
record Paid(long totalPaise) implements OrderState {}
record Shipped(long totalPaise, String trackingId) implements OrderState {}
record Cancelled(String reason, boolean refundDue) implements OrderState {}

sealed interface OrderEvent permits PlaceOrder, Pay, Ship, Cancel {}
record PlaceOrder(long totalPaise) implements OrderEvent {}
record Pay(long amountPaise) implements OrderEvent {}
record Ship(String trackingId) implements OrderEvent {}
record Cancel(String reason) implements OrderEvent {}

final class OrderMachine {
    private record Step(OrderState state, OrderEvent event) {}

    static OrderState apply(OrderState state, OrderEvent event) {
        return switch (new Step(state, event)) {
            case Step(NewOrder n, PlaceOrder(long total)) when total > 0 -> new Placed(total);
            case Step(Placed(long total), Pay(long amount)) when amount == total -> new Paid(total);
            case Step(Placed(long total), Pay(long amount)) ->
                throw new IllegalArgumentException("payment " + amount + " does not match total " + total);
            case Step(Paid(long total), Ship(String tracking)) -> new Shipped(total, tracking);
            case Step(Placed p, Cancel(String reason)) -> new Cancelled(reason, false);
            case Step(Paid p, Cancel(String reason)) -> new Cancelled(reason, true);      // money must be refunded
            case Step(OrderState s, OrderEvent e) -> throw new IllegalStateException(
                e.getClass().getSimpleName() + " not allowed in " + s.getClass().getSimpleName());
        };
    }

    static String describe(OrderState s) {
        return switch (s) {                                  // exhaustive: no default
            case NewOrder n -> "draft";
            case Placed(long t) -> "awaiting payment of " + t;
            case Paid(long t) -> "paid " + t + ", ready to ship";
            case Shipped(long t, String tracking) -> "shipped, tracking " + tracking;
            case Cancelled(String reason, boolean refund) -> "cancelled (" + reason + ")" + (refund ? ", refund due" : "");
        };
    }
}

class OrderMachineDemo {
    public static void main(String[] args) {
        OrderState s = new NewOrder();
        for (OrderEvent e : java.util.List.of(new PlaceOrder(49_900), new Pay(49_900), new Ship("AWB123"))) {
            s = OrderMachine.apply(s, e);
            System.out.println(OrderMachine.describe(s));
        }
        OrderState paid = OrderMachine.apply(OrderMachine.apply(new NewOrder(), new PlaceOrder(100)), new Pay(100));
        System.out.println(OrderMachine.describe(OrderMachine.apply(paid, new Cancel("customer request"))));
        try { OrderMachine.apply(s, new Cancel("too late")); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }
        try { OrderMachine.apply(new Placed(100), new Pay(90)); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }

        OrderStrings legacy = new OrderStrings();
        legacy.apply("PLACE", "100"); legacy.apply("PAY", "100"); legacy.apply("SHIP", "AWB9");
        System.out.println(legacy.status + " " + Status.NEW.on("PLACE").on("PAY").on("SHIP"));   // SHIPPED SHIPPED
    }
}

Feasible → optimal

All are O(1) per event. Strings are feasible but unsafe; enum states are type-safe but lose per-state data; sealed states plus record patterns over (state, event) pairs give type-safe data, explicit business rules, and an exhaustive describe. In a real service the transition function stays pure like this, and the caller persists the new state with optimistic locking and publishes an event via the outbox.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is a pure transition function (state, event) → state a good design?

It has no I/O, so every rule is unit-testable with plain values, it can be replayed from an event log (event sourcing), and concurrency is handled outside it (load state with a version, apply, save with a version check). Side effects such as emails or refunds are triggered from the resulting state or events after commit, not hidden inside the rules.

When would you use a workflow engine instead?

When the process spans services and time: waiting days for a payment, timers and reminders, retries of external calls, compensation, and human steps. Temporal, Camunda or AWS Step Functions persist state and timers durably; the pattern-matched transition function above is ideal for the in-process rules of a single aggregate.