State Pattern
Some objects answer the same request differently depending on what has already happened to them. A vending machine ignores the item buttons until you have paid. An ATM won't let you withdraw before you have entered your PIN. An order can be cancelled while it is being packed, but not after it has shipped. The request is the same; the object's current state decides what it means.
The State pattern gives each state its own class. The object holds its current state and forwards every request to it, and each state decides what the request does right now and which state comes next. Whenever an interview prompt describes something with modes, statuses or a lifecycle, this is the pattern your interviewer is waiting to hear about.
🚦 In one sentence: put the behavior of each state in its own class behind one interface, let the object delegate to its current state, and let the states switch the object from one state to the next as events happen.
The Problem It Solves
Here is a vending machine written the way it usually starts: a state string and an if at the top of every
method.
class VendingMachine:
def __init__(self, prices: dict[str, int]) -> None:
self.prices = prices
self.stock: dict[str, int] = {}
self.balance = 0
self.state = "sold_out" # idle | has_money | sold_out
def insert_coin(self, cents: int) -> None:
if self.state == "sold_out":
raise ValueError("sold out, coin returned")
self.balance += cents
self.state = "has_money"
def select(self, item: str) -> int:
if self.state == "idle":
raise ValueError("insert money first")
if self.state == "sold_out":
raise ValueError("sold out")
price = self.prices[item]
if self.stock.get(item, 0) == 0 or self.balance < price:
raise ValueError("pick another item or add money")
self.stock[item] -= 1
change, self.balance = self.balance - price, 0
self.state = "sold_out" if sum(self.stock.values()) == 0 else "idle"
return change
def cancel(self) -> int:
if self.state != "has_money":
return 0
refund, self.balance = self.balance, 0
self.state = "idle"
return refund
With three states and three buttons it is readable. Here is what goes wrong as it grows.
Every method switches on the same field. Three states times three methods is nine cases, spread across three
if chains. Adding a "maintenance" state means editing every method, and the one you forget is a bug: here,
insert_coin would happily take money from a customer during maintenance.
The transitions are hidden. To find out where has_money can go next, you read every method and look for
assignments to self.state. Nothing in the code says "idle goes to has_money when a coin arrives".
Illegal transitions are easy to write. Any line can set self.state to anything, and a typo like
"has-money" creates a new state that no method handles.
State-specific data has nowhere to live. An ATM counts wrong PIN attempts, but that counter only means something while a card is inside. In this style it becomes a field on the whole machine that someone has to remember to reset.
⚠️ The smell to look for: the same status field checked at the top of several methods, with each method also changing it. That is a state machine hiding in
ifstatements, and the cue for the State pattern.