State: objects that change behaviour with status
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite order must not be cancelled once it is delivered, but every method repeats its own switch on the status, and one forgotten case allows it. How can the rules for each status live in one place?
The problem: a status switch in every method
State pattern is a design pattern where an object hands each action to a state object that stands for its current status, and each status is its own class. The state decides what the action does and which status comes next.
A ShopLite order moves through placed, paid, shipped, delivered or cancelled. Below, every method has its own switch on a String status.
Example 1 · Before: a status switch in every method, with a bug
class Order { private final String id; private String status = "PLACED";
Order(String id) { this.id = id; }
void pay() { switch (status) { case "PLACED" -> status = "PAID"; default -> System.out.println(" cannot pay when " + status); } }
void ship() { switch (status) { case "PAID" -> status = "SHIPPED"; default -> System.out.println(" cannot ship when " + status); } }
void deliver() { switch (status) { case "SHIPPED" -> status = "DELIVERED"; default -> System.out.println(" cannot deliver when " + status); } }
void cancel() { switch (status) { case "SHIPPED" -> System.out.println(" cannot cancel when " + status); default -> status = "CANCELLED"; // forgot DELIVERED and CANCELLED } }
String status() { return id + " is " + status; }}
public class StatusSwitchDemo { public static void main(String[] args) { Order order = new Order("A101"); order.pay(); order.ship(); order.deliver(); System.out.println(order.status()); order.cancel(); System.out.println(order.status()); }}A101 is DELIVERED A101 is CANCELLED
What this code does
- Each method has its own
switchover the same statuses. The rules for "delivered" are spread over four methods, so it is easy to miss one. cancellists only the case it blocks, and itsdefaultlets a delivered order become cancelled. Nothing warns about the missing cases.
Every method repeats the same list of statuses, and the rules for one status are spread over four methods. Adding a status means editing all of them, and one forgotten case quietly allows something impossible, such as cancelling a delivered order.
State interface with one class per status
State is a class that stands for one status of an object and holds all the rules for it. The state interface lists every action (pay, ship, deliver, cancel), and each status, such as Paid, is a concrete state class.
Each status becomes a small class, and Order forwards every action to the one it currently holds. Below is one order's happy path.
Example 2 · State classes: the happy path of one order
interface OrderState { String name(); void pay(Order order); void ship(Order order); void deliver(Order order); void cancel(Order order);}
abstract class BaseState implements OrderState { // every action is illegal by default public void pay(Order order) { reject("pay"); } public void ship(Order order) { reject("ship"); } public void deliver(Order order) { reject("deliver"); } public void cancel(Order order) { reject("cancel"); }
protected void reject(String action) { throw new IllegalStateException("cannot " + action + " an order that is " + name()); }}
class Placed extends BaseState { public String name() { return "PLACED"; } public void pay(Order order) { order.moveTo(new Paid()); } public void cancel(Order order) { order.moveTo(new Cancelled()); }}
class Paid extends BaseState { public String name() { return "PAID"; } public void ship(Order order) { order.moveTo(new Shipped()); }
public void cancel(Order order) { System.out.println(" refund of Rs " + order.amount() + " started"); order.moveTo(new Cancelled()); }}
class Shipped extends BaseState { public String name() { return "SHIPPED"; } public void deliver(Order order) { order.moveTo(new Delivered()); }}
class Delivered extends BaseState { public String name() { return "DELIVERED"; }}
class Cancelled extends BaseState { public String name() { return "CANCELLED"; }}
class Order { // the context private final String id; private final int amount; private OrderState state = new Placed();
Order(String id, int amount) { this.id = id; this.amount = amount; }
void moveTo(OrderState next) { System.out.println(" " + id + ": " + state.name() + " -> " + next.name()); state = next; }
void pay() { state.pay(this); } void ship() { state.ship(this); } void deliver() { state.deliver(this); } void cancel() { state.cancel(this); }
int amount() { return amount; } String status() { return state.name(); }}
public class StateClassesDemo { public static void main(String[] args) { Order order = new Order("A101", 1799); System.out.println("Status: " + order.status()); order.pay(); order.ship(); order.deliver(); System.out.println("Status: " + order.status()); }}Status: PLACED A101: PLACED -> PAID A101: PAID -> SHIPPED A101: SHIPPED -> DELIVERED Status: DELIVERED
What this code does
Orderhas noswitchat all. Each call goes to the current state object, and that state callsmoveTowith the next one.BaseStaterejects every action, so each state class lists only the moves it allows:Placedallows pay and cancel,Shippedonly deliver.
The order is called the context: it holds the current state and forwards every action to it. All the rules for one status now live in one class, so to see what can happen to a shipped order you read Shipped and nothing else.
A shared base class can reject every action by default, so each state lists only the moves it allows.
Transitions owned by the states, illegal actions rejected
Transition is a move from one status to another, such as Placed to Paid. In the State pattern the current state decides it: Placed.pay() moves the order to Paid.
The current state decides the next one, and an action it does not allow is rejected. Below, wrong moves get a clear message and a paid order is refunded on cancel.
Example 3 · Illegal actions are rejected, and cancel refunds when paid
interface OrderState { String name(); void pay(Order order); void ship(Order order); void deliver(Order order); void cancel(Order order);}
abstract class BaseState implements OrderState { // every action is illegal by default public void pay(Order order) { reject("pay"); } public void ship(Order order) { reject("ship"); } public void deliver(Order order) { reject("deliver"); } public void cancel(Order order) { reject("cancel"); }
protected void reject(String action) { throw new IllegalStateException("cannot " + action + " an order that is " + name()); }}
class Placed extends BaseState { public String name() { return "PLACED"; } public void pay(Order order) { order.moveTo(new Paid()); } public void cancel(Order order) { order.moveTo(new Cancelled()); }}
class Paid extends BaseState { public String name() { return "PAID"; } public void ship(Order order) { order.moveTo(new Shipped()); }
public void cancel(Order order) { System.out.println(" refund of Rs " + order.amount() + " started"); order.moveTo(new Cancelled()); }}
class Shipped extends BaseState { public String name() { return "SHIPPED"; } public void deliver(Order order) { order.moveTo(new Delivered()); }}
class Delivered extends BaseState { public String name() { return "DELIVERED"; }}
class Cancelled extends BaseState { public String name() { return "CANCELLED"; }}
class Order { // the context private final String id; private final int amount; private OrderState state = new Placed();
Order(String id, int amount) { this.id = id; this.amount = amount; }
void moveTo(OrderState next) { System.out.println(" " + id + ": " + state.name() + " -> " + next.name()); state = next; }
void pay() { state.pay(this); } void ship() { state.ship(this); } void deliver() { state.deliver(this); } void cancel() { state.cancel(this); }
int amount() { return amount; } String status() { return state.name(); }}
public class IllegalMovesDemo { static void attempt(String label, Runnable action) { try { action.run(); } catch (IllegalStateException e) { System.out.println(" rejected (" + label + "): " + e.getMessage()); } }
public static void main(String[] args) { Order a = new Order("A101", 1799); attempt("ship first", a::ship); a.pay(); attempt("pay twice", a::pay); a.cancel(); // paid, so a refund starts attempt("ship cancelled", a::ship);
Order b = new Order("A102", 391); b.pay(); b.ship(); attempt("cancel shipped", b::cancel); b.deliver(); attempt("cancel delivered", b::cancel); System.out.println(a.status() + ", " + b.status()); }}rejected (ship first): cannot ship an order that is PLACED A101: PLACED -> PAID rejected (pay twice): cannot pay an order that is PAID refund of Rs 1799 started A101: PAID -> CANCELLED rejected (ship cancelled): cannot ship an order that is CANCELLED A102: PLACED -> PAID A102: PAID -> SHIPPED rejected (cancel shipped): cannot cancel an order that is SHIPPED A102: SHIPPED -> DELIVERED rejected (cancel delivered): cannot cancel an order that is DELIVERED CANCELLED, DELIVERED
What this code does
- Every wrong move gets the same clear message, built in one place:
BaseState.reject. The order's status never changes on a rejected action. - Only
Paid.cancelknows a refund is needed.Placed.cancelsimply cancels, because nothing was charged yet.
Side effects that belong to a transition live in that state too: Paid.cancel() starts a refund before moving to Cancelled.
A base class that rejects everything makes a new state safe by default: it allows only what it explicitly overrides.
Predict the output
Predict the rejected move
Read the code, then pick what it prints.
A new order is paid, shipped and then paid again.
switch branch. With a rejecting base class, an action is illegal simply by not being overridden.An enum-based state machine as a lighter alternative
Transition table is a map from each status to the set of statuses it may move to. With an enum of statuses, it holds all the move rules in a few readable lines.
When statuses have rules but no special behaviour, an enum and a transition table are enough. Below, moveTo checks the table before it changes anything.
Example 4 · A lighter version: enum plus a transition table
import java.util.EnumMap;import java.util.Map;import java.util.Set;
enum OrderStatus { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED }
class Order { private static final Map<OrderStatus, Set<OrderStatus>> ALLOWED = new EnumMap<>(Map.of( OrderStatus.PLACED, Set.of(OrderStatus.PAID, OrderStatus.CANCELLED), OrderStatus.PAID, Set.of(OrderStatus.SHIPPED, OrderStatus.CANCELLED), OrderStatus.SHIPPED, Set.of(OrderStatus.DELIVERED), OrderStatus.DELIVERED, Set.of(), OrderStatus.CANCELLED, Set.of()));
private final String id; private OrderStatus status = OrderStatus.PLACED;
Order(String id) { this.id = id; }
void moveTo(OrderStatus next) { if (!ALLOWED.get(status).contains(next)) { throw new IllegalStateException(id + ": " + status + " -> " + next + " is not allowed"); } System.out.println(" " + id + ": " + status + " -> " + next); status = next; }}
public class EnumStateDemo { public static void main(String[] args) { Order order = new Order("A101"); OrderStatus[] steps = { OrderStatus.PAID, OrderStatus.SHIPPED, OrderStatus.CANCELLED, OrderStatus.DELIVERED }; for (OrderStatus step : steps) { try { order.moveTo(step); } catch (IllegalStateException e) { System.out.println(" rejected: " + e.getMessage()); } } }}A101: PLACED -> PAID A101: PAID -> SHIPPED rejected: A101: SHIPPED -> CANCELLED is not allowed A101: SHIPPED -> DELIVERED
What this code does
- All the rules are in one table: each status maps to the statuses it may move to.
moveTochecks the table before changing anything. - This fits when transitions carry no extra logic. The refund on cancel from the previous example would need an
ifhere, which is the sign to move to state classes.
The table is easy to read, to print and to test, and an EnumMap is fast. Move up to state classes when the statuses start to carry their own logic, such as refunds, emails or different prices.
Find the bug
Spot the table bug
Each snippet has one wrong line. Tap it, then read the fix.
A shipped order must not be cancellable.
Round 1 of 2Drawing the state diagram before coding
State diagram is a drawing with each status as a box and each allowed transition as an arrow labelled with its action. Drawing it first catches questions such as: can a shipped order be cancelled?
Draw the diagram before coding, then print it from the code. Below, the table is printed and every possible move is tested.
Example 5 · Print the diagram and test every move from the code
import java.util.EnumMap;import java.util.EnumSet;import java.util.Map;import java.util.Set;
enum OrderStatus { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED }
public class StateDiagramDemo { static final Map<OrderStatus, Set<OrderStatus>> ALLOWED = new EnumMap<>(Map.of( OrderStatus.PLACED, EnumSet.of(OrderStatus.PAID, OrderStatus.CANCELLED), OrderStatus.PAID, EnumSet.of(OrderStatus.SHIPPED, OrderStatus.CANCELLED), OrderStatus.SHIPPED, EnumSet.of(OrderStatus.DELIVERED), OrderStatus.DELIVERED, EnumSet.noneOf(OrderStatus.class), OrderStatus.CANCELLED, EnumSet.noneOf(OrderStatus.class)));
public static void main(String[] args) { System.out.println("State diagram:"); for (Map.Entry<OrderStatus, Set<OrderStatus>> e : ALLOWED.entrySet()) { String arrows = e.getValue().isEmpty() ? "(final)" : "-> " + e.getValue(); System.out.printf(" %-9s %s%n", e.getKey(), arrows); }
int allowed = 0; int rejected = 0; for (OrderStatus from : OrderStatus.values()) { for (OrderStatus to : OrderStatus.values()) { if (ALLOWED.get(from).contains(to)) allowed++; else rejected++; } } System.out.println("Moves to test: " + allowed + " allowed, " + rejected + " rejected"); }}State diagram: PLACED -> [PAID, CANCELLED] PAID -> [SHIPPED, CANCELLED] SHIPPED -> [DELIVERED] DELIVERED (final) CANCELLED (final) Moves to test: 5 allowed, 20 rejected
What this code does
EnumMapandEnumSetkeep the statuses in declaration order, so the printout reads like the diagram from top to bottom. States with no arrows out are final.- Five statuses give 25 possible moves. Each of the 5 arrows must work and each of the other 20 must be rejected; that list is your test plan.
The diagram is also a test plan: every arrow is a move that must work, and every missing arrow is a move that must be rejected. A status with no arrows out is a final state, such as DELIVERED or CANCELLED.
A small program can print the table from the code, so the diagram and the code never drift apart.
Order of execution
From diagram to tests
Put the steps in the order you would do them.
Next step
Check your understanding
12 quick questions