Video in progress
Order statuses have multiplied and the code is full of `switch`es. How does the State pattern help here?
The State pattern moves each state into its own class, and that class itself decides which actions are allowed in that state. Then the switch (status) in every method disappears, and invalid transitions are controlled in one place.
📖 Answer
The usual picture: cancel(), pay(), ship(), refund(), each with a switch (order.getStatus()). When a new status is added, you have to find and change five places, and you'll forget one.
With State:
sealed interface OrderState permits New, Paid, Shipped, Cancelled {
default OrderState pay() { throw illegal("pay"); }
default OrderState ship() { throw illegal("ship"); }
default OrderState cancel() { throw illegal("cancel"); }
}
record New() implements OrderState {
public OrderState pay() { return new Paid(); }
public OrderState cancel() { return new Cancelled(); }
}
record Paid() implements OrderState {
public OrderState ship() { return new Shipped(); }
public OrderState cancel() { return new Cancelled(); } // the refund comes later
}
Inside Order it's just state = state.pay();. A disallowed transition throws an exception automatically.
Practical points:
- You don't store the state class in the database but the enum, and on load you convert the enum to a state object. Sometimes the enum itself plays the State by overriding a method for each constant: for small sets of states that's the most compact.
- If the states grow past 10 and the transitions get complicated, consider a declarative state machine (in table form) or a library like Spring Statemachine.
- If two requests make a transition at the same time, you need an optimistic lock (
@Version): the pattern doesn't solve that.
Sign up to mark studied questions and save your progress.