Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Implement an order lifecycle with states NEW, PAID, SHIPPED and CANCELLED, where only valid transitions are allowed (for example SHIPPED cannot become CANCELLED). Show a Java approach.

We model the states as an enum OrderStatus where each state knows its allowed next states, through a canTransitionTo method backed by an EnumMap or EnumSet. The Order class keeps its status field private and exposes intention-revealing methods such as pay(), ship() and cancel(), each of which checks the transition and throws on an invalid move, so SHIPPED can never become CANCELLED. We write a test for every allowed and every forbidden transition, and note that the classic state pattern, one class per state with its own behaviour, is only worth it when states behave very differently; for a simple lifecycle the enum is enough.

Why this question is asked

Order status bugs are some of the most expensive bugs in commerce systems. An order that is cancelled after it has shipped means a refund for goods the customer has, and a paid order that goes back to NEW may be charged twice. These bugs usually come from code that sets the status directly, order.setStatus(CANCELLED), from many places, with each place checking a different set of conditions or none. Interviewers ask this coding question because it shows whether we can make invalid states impossible to reach, rather than hoping every caller remembers the rules. In this answer, we will see the broken version, define the transitions in the enum, wrap them in intention-revealing methods on Order, test every transition, and compare with the classic state pattern.

1The Problem With a Public Status Setter

Here is what we want to avoid. The status can be set by anyone, and the rule that a shipped order cannot be cancelled exists only in the heads of developers.

Java
public class Order {
private OrderStatus status = OrderStatus.NEW;
public void setStatus(OrderStatus s) { this.status = s; } // anyone can set anything
}
order.setStatus(OrderStatus.SHIPPED);
order.setStatus(OrderStatus.CANCELLED); // allowed: the customer is refunded and keeps the parcel

The fix has two parts. First, write the rules down in one place, as data the code can check. Second, remove every way of changing the status that does not go through that check.

2Defining the Allowed Transitions in the Enum

A transition is a move from one state to another. For our lifecycle, NEW can go to PAID or CANCELLED, PAID can go to SHIPPED or CANCELLED (with a refund), and SHIPPED and CANCELLED are final states, with no moves out of them. We let each enum constant answer whether a move is allowed.

Java
public enum OrderStatus {
NEW, PAID, SHIPPED, CANCELLED;
private static final Map<OrderStatus, Set<OrderStatus>> NEXT = new EnumMap<>(OrderStatus.class);
static {
NEXT.put(NEW, EnumSet.of(PAID, CANCELLED));
NEXT.put(PAID, EnumSet.of(SHIPPED, CANCELLED));
NEXT.put(SHIPPED, EnumSet.noneOf(OrderStatus.class));
NEXT.put(CANCELLED, EnumSet.noneOf(OrderStatus.class));
}
public boolean canTransitionTo(OrderStatus next) { return NEXT.get(this).contains(next); }
public boolean isFinal() { return NEXT.get(this).isEmpty(); }
}
OrderStatus.NEW.canTransitionTo(OrderStatus.PAID); // true
OrderStatus.SHIPPED.canTransitionTo(OrderStatus.CANCELLED); // false
OrderStatus.PAID.canTransitionTo(OrderStatus.NEW); // false
Allowed transitions for an order
FromTo PAIDTo SHIPPEDTo CANCELLED
NEWallowed: pay()noallowed: cancel()
PAIDnoallowed: ship()allowed: cancel(), refund
SHIPPEDnonono: return process instead
CANCELLEDnonono

Notice why the map is built in a static block after the constants rather than passed to the enum constructor. A constructor argument such as EnumSet.of(PAID) inside the declaration of NEW would refer to PAID before it exists, which does not compile. The static block runs after all constants are created, so it can refer to any of them. EnumMap and EnumSet are backed by arrays and bit sets, so these lookups are as fast as a field read.

3Intention-Revealing Methods on Order

Callers should not pick a target state at all. They should say what happened in business terms: the customer paid, the warehouse shipped, the customer cancelled. Methods with those names, pay(), ship() and cancel(), read like the business process, and each one checks the transition before changing anything. The status field stays private, and there is no setter, so the only way to change it is through these methods.

Java
public class Order {
private OrderStatus status = OrderStatus.NEW;
private Instant paidAt, shippedAt;
public void pay(Instant when) { moveTo(OrderStatus.PAID); paidAt = when; }
public void ship(Instant when) { moveTo(OrderStatus.SHIPPED); shippedAt = when; }
public void cancel() { moveTo(OrderStatus.CANCELLED); }
public OrderStatus status() { return status; } // read-only view
private void moveTo(OrderStatus next) {
if (!status.canTransitionTo(next)) {
throw new IllegalStateException("Cannot move order from " + status + " to " + next);
}
status = next;
}
}
Order o = new Order();
o.pay(Instant.now()); // NEW -> PAID
o.ship(Instant.now()); // PAID -> SHIPPED
o.cancel(); // IllegalStateException: Cannot move order from SHIPPED to CANCELLED
System.out.println(o.status()); // SHIPPED: unchanged after the failed move

Notice that moveTo checks before changing anything, so a failed move leaves the order exactly as it was. Notice also that each method can do the extra work its event needs, such as recording paidAt, which a generic setter could never know about. If we use JPA, the entity can still have a status column; we just give it field access and no public setter, and add a @Version field so two concurrent requests cannot both move the same order.

4Testing Every Transition

With four states there are sixteen pairs of from and to, few enough to test them all. A parameterised test over every pair compares canTransitionTo with an expected table written separately in the test. That catches someone adding a transition to the enum by mistake, because the test's table will disagree.

Java
static Stream<Arguments> allPairs() {
Set<String> allowed = Set.of("NEW>PAID", "NEW>CANCELLED", "PAID>SHIPPED", "PAID>CANCELLED");
return Arrays.stream(OrderStatus.values()).flatMap(from ->
Arrays.stream(OrderStatus.values()).map(to ->
Arguments.of(from, to, allowed.contains(from + ">" + to))));
}
@ParameterizedTest(name = "{0} -> {1} allowed={2}")
@MethodSource("allPairs")
void transitions(OrderStatus from, OrderStatus to, boolean expected) {
assertEquals(expected, from.canTransitionTo(to));
}
// 16 tests: 4 allowed, 12 forbidden, including SHIPPED -> CANCELLED
@Test
void cancelAfterShipIsRejected() {
Order o = new Order(); o.pay(Instant.now()); o.ship(Instant.now());
assertThrows(IllegalStateException.class, o::cancel);
assertEquals(OrderStatus.SHIPPED, o.status());
}

The second test checks the methods on Order, including that a rejected move does not change the status. Together they document the lifecycle better than any comment.

5The Classic State Pattern and When It Is Worth It

The classic state pattern goes further: each state is a class, such as NewState, PaidState and ShippedState, implementing one interface with methods like pay(), ship() and cancel(). The order delegates each call to its current state object, and each state either does the work and returns the next state, or throws. The behaviour of each state lives in its own class.

That structure pays off when states behave very differently, for example when shipping a paid order reserves stock and books a courier, while the same call on a pre-order schedules it for later, and those behaviours have many lines and dependencies of their own. For a lifecycle where the states differ mainly in which moves are allowed, as here, four classes add reading cost with little benefit, and the transition table in the enum is easier to review at a glance. Java enums can also carry per-constant methods, a middle ground when only a little behaviour differs.

6Follow-up questions

How would you persist the status with JPA?

Map it with @Enumerated(EnumType.STRING), so the database stores NEW or PAID rather than ordinal numbers that break when constants are reordered. Keep the field private with no setter, add @Version for optimistic locking, and let the domain methods be the only way to change it.

What about a transition from SHIPPED back to something, like a return?

A return is a new business event, not an undo of shipping. We would add states such as RETURN_REQUESTED and RETURNED with their own transitions from SHIPPED, and a method requestReturn(). That keeps the history truthful: the order was shipped, and then returned.

Would a sealed interface with records be better than an enum?

It is useful when each state carries different data, for example a Shipped state with a tracking number and a Cancelled state with a reason. Then each state is a record, and transitions are methods that return a new state. For states that carry no data of their own, an enum is simpler.

7Conclusion

In this answer, we replaced a public status setter with an OrderStatus enum that knows its allowed next states through an EnumMap, and an Order whose status field is private and changes only through pay(), ship() and cancel(), each checking the transition and throwing on invalid moves such as SHIPPED to CANCELLED. We tested every one of the sixteen transitions, and saw that the classic state pattern with one class per state is worth it only when states behave very differently.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start by putting the rules in one place. OrderStatus is an enum with NEW, PAID, SHIPPED and CANCELLED, and a static EnumMap from each state to an EnumSet of allowed next states: NEW can go to PAID or CANCELLED, PAID to SHIPPED or CANCELLED, and SHIPPED and CANCELLED are final.

Then, if they want more

The enum exposes canTransitionTo. I build the map in a static block because the constants cannot refer to each other in their own constructor arguments. Then the Order class keeps the status field private with no setter. Instead it has intention-revealing methods, pay, ship and cancel, that describe business events.

Each calls a private moveTo that checks canTransitionTo and throws IllegalStateException with the from and to states if the move is invalid, and only then changes the status. So cancelling a shipped order throws, and the order stays SHIPPED. Those methods are also where event-specific data goes, like the time it was paid.

With JPA I would store the enum as a string and add a version column so concurrent requests cannot both move the same order. For tests, four states means sixteen pairs, so I would write a parameterised test over every pair against an expected table, plus a few tests on the Order methods.

The classic state pattern, with one class per state, is the alternative, but I would only use it if states had substantially different behaviour. For a lifecycle where states mostly differ in allowed moves, the enum and transition table is clearer.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement an order lifecycle with states NEW, PAID, SHIPPED and CANCELLED, where only...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/0610f8fb1d/