State: What You Can Do Depends on Where It Is
When every method of a package starts by checking its status, a new status means editing every method, and the one you miss breaks a rule; drawing the rules as a state diagram, then giving each status its own class, puts each status's rules in one place: the State pattern.
Journeyman · OOP · Updated
After this lesson you can
- Read and draw a state diagram: states, the events on its arrows, and the start dot
- Turn a status check repeated in every method into one class per state, each deciding what it allows
- Spot the smells that point to State: the same status check in every method, growing with each new status
Key takeaways
- The smell: the same status check at the top of every method, so the rules for one status are spread across all of them.
- A state diagram draws the rules: rounded boxes for the states, arrows labeled with the events that move between them, and a dot for the start. No arrow means "not allowed from here".
- The fix: one class per state, each saying what it allows and where it leads; the package hands every request to its current state.
- A new status is one new class, and the statuses you didn't touch can't break.
- When each status only decides where it goes next, a table of moves can do the same job in a few lines.
Before this: Meet the Package Tracker, where a package's status is a word, and Delegation: Handing the Job On, where one object passes work to another it holds.
The customer website wants a Cancel button. That sounds like one small method. But you can cancel a package only while it's ordered, you can return it only once it's delivered, and the depot can load it onto a van only after it has shipped. What a package can do depends on where it is. This lesson follows that rule into the code, draws it as a new kind of diagram, and ends with a pattern called State.
The symptom: the same check in every method
The tracker's Package now has a method for each thing that can happen to it, and each method checks the status before it does anything. Cancel was written early, when the only statuses were ordered, shipped and delivered. out for delivery came later. Here's Maya clicking Cancel while Dana's van is already on its way:
Package parcel = new Package(42);
Console.WriteLine(parcel.Ship());
Console.WriteLine(parcel.Cancel());
Console.WriteLine(parcel.Load());
Console.WriteLine(parcel.Cancel());
Console.WriteLine(parcel.DropOff());
Console.WriteLine(parcel.ReturnPackage());
class Package
{
public int Id { get; }
public string Status { get; private set; } = "ordered";
public Package(int id) { Id = id; }
public string Ship()
{
if (Status == "ordered") { return MoveTo("shipped"); }
return Refuse("ship");
}
public string Load()
{
if (Status == "shipped") { return MoveTo("out for delivery"); }
return Refuse("load");
}
public string DropOff()
{
if (Status == "out for delivery") { return MoveTo("delivered"); }
return Refuse("drop off");
}
public string ReturnPackage()
{
if (Status == "delivered") { return MoveTo("returned"); }
return Refuse("return");
}
public string Cancel()
{
// Written when the only statuses were ordered, shipped and delivered.
if (Status != "shipped" && Status != "delivered") { return MoveTo("canceled"); }
return Refuse("cancel");
}
private string MoveTo(string status)
{
Status = status;
return quot;Package {Id}: {Status}";
}
private string Refuse(string action) => quot;Package {Id}: can't {action}, it's {Status}";
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: canceled
Package 42: can't drop off, it's canceled
Package 42: can't return, it's canceled
class Package {
int id;
String status = "ordered";
Package(int id) { this.id = id; }
String ship() {
if (status.equals("ordered")) { return moveTo("shipped"); }
return refuse("ship");
}
String load() {
if (status.equals("shipped")) { return moveTo("out for delivery"); }
return refuse("load");
}
String dropOff() {
if (status.equals("out for delivery")) { return moveTo("delivered"); }
return refuse("drop off");
}
String returnPackage() {
if (status.equals("delivered")) { return moveTo("returned"); }
return refuse("return");
}
String cancel() {
// Written when the only statuses were ordered, shipped and delivered.
if (!status.equals("shipped") && !status.equals("delivered")) { return moveTo("canceled"); }
return refuse("cancel");
}
String moveTo(String next) {
status = next;
return "Package " + id + ": " + status;
}
String refuse(String action) { return "Package " + id + ": can't " + action + ", it's " + status; }
}
void main() {
Package parcel = new Package(42);
IO.println(parcel.ship());
IO.println(parcel.cancel());
IO.println(parcel.load());
IO.println(parcel.cancel());
IO.println(parcel.dropOff());
IO.println(parcel.returnPackage());
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: canceled
Package 42: can't drop off, it's canceled
Package 42: can't return, it's canceled
class Package:
def __init__(self, id):
self.id = id
self.status = "ordered"
def ship(self):
if self.status == "ordered":
return self._move_to("shipped")
return self._refuse("ship")
def load(self):
if self.status == "shipped":
return self._move_to("out for delivery")
return self._refuse("load")
def drop_off(self):
if self.status == "out for delivery":
return self._move_to("delivered")
return self._refuse("drop off")
def return_package(self):
if self.status == "delivered":
return self._move_to("returned")
return self._refuse("return")
def cancel(self):
# Written when the only statuses were ordered, shipped and delivered.
if self.status != "shipped" and self.status != "delivered":
return self._move_to("canceled")
return self._refuse("cancel")
def _move_to(self, status):
self.status = status
return f"Package {self.id}: {self.status}"
def _refuse(self, action):
return f"Package {self.id}: can't {action}, it's {self.status}"
parcel = Package(42)
print(parcel.ship())
print(parcel.cancel())
print(parcel.load())
print(parcel.cancel())
print(parcel.drop_off())
print(parcel.return_package())
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: canceled
Package 42: can't drop off, it's canceled
Package 42: can't return, it's canceled
class Package {
status = "ordered";
constructor(id) {
this.id = id;
}
ship() {
if (this.status === "ordered") { return this.moveTo("shipped"); }
return this.refuse("ship");
}
load() {
if (this.status === "shipped") { return this.moveTo("out for delivery"); }
return this.refuse("load");
}
dropOff() {
if (this.status === "out for delivery") { return this.moveTo("delivered"); }
return this.refuse("drop off");
}
returnPackage() {
if (this.status === "delivered") { return this.moveTo("returned"); }
return this.refuse("return");
}
cancel() {
// Written when the only statuses were ordered, shipped and delivered.
if (this.status !== "shipped" && this.status !== "delivered") { return this.moveTo("canceled"); }
return this.refuse("cancel");
}
moveTo(next) {
this.status = next;
return `Package ${this.id}: ${this.status}`;
}
refuse(action) {
return `Package ${this.id}: can't ${action}, it's ${this.status}`;
}
}
const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.cancel());
console.log(parcel.load());
console.log(parcel.cancel());
console.log(parcel.dropOff());
console.log(parcel.returnPackage());
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: canceled
Package 42: can't drop off, it's canceled
Package 42: can't return, it's canceled
class Package {
id: number;
status = "ordered";
constructor(id: number) {
this.id = id;
}
ship(): string {
if (this.status === "ordered") { return this.moveTo("shipped"); }
return this.refuse("ship");
}
load(): string {
if (this.status === "shipped") { return this.moveTo("out for delivery"); }
return this.refuse("load");
}
dropOff(): string {
if (this.status === "out for delivery") { return this.moveTo("delivered"); }
return this.refuse("drop off");
}
returnPackage(): string {
if (this.status === "delivered") { return this.moveTo("returned"); }
return this.refuse("return");
}
cancel(): string {
// Written when the only statuses were ordered, shipped and delivered.
if (this.status !== "shipped" && this.status !== "delivered") { return this.moveTo("canceled"); }
return this.refuse("cancel");
}
moveTo(next: string): string {
this.status = next;
return `Package ${this.id}: ${this.status}`;
}
refuse(action: string): string {
return `Package ${this.id}: can't ${action}, it's ${this.status}`;
}
}
const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.cancel());
console.log(parcel.load());
console.log(parcel.cancel());
console.log(parcel.dropOff());
console.log(parcel.returnPackage());
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: canceled
Package 42: can't drop off, it's canceled
Package 42: can't return, it's canceled
The fourth line is a real bug: the van is on its way and the package was canceled anyway, so Dana can't drop it off. Nobody edited Cancel when out for delivery was added. Nobody knew they had to.
- The symptom: every method starts with the same question, "what's my status?", so the rules for one status are spread across five methods.
- The cause: the statuses are words, and each method keeps its own idea of which words it allows. A new status means visiting every method, and the one you miss is wrong without anyone touching it.
The depot already has the next one waiting: held at the depot, for packages that need a signature nobody was home for.
What would you try?
Fix Cancel's check. Add && Status != "out for delivery". That fixes today's bug. Next month, held at the depot arrives, and every check written with != needs it too.
One big method with a nested switch, on the status and then on the action. Every rule is in one place now, but it's one enormous place: it grows in two directions, and every change touches the method that handles everything.
An enum instead of words. PackageStatus.Shipped catches typos, and that's worth having, but every method still checks it, so the same rules are still spread across five methods.
What would really help: all the rules for one status in one place. "What can a shipped package do?" should have one answer, in one spot, and a new status should be a new spot, not edits to five methods.
The everyday version: a washing machine
A washing machine has one button, and what it does depends on where the machine is in its cycle. When it's ready, the button starts it. While it's washing, the same button pauses it. When it's paused, the button carries on. The door opens only when it's done. Nobody tapes a list of rules to the button; the machine's state decides.

Draw it first: a state diagram
Before fixing the code, draw the rules. A state diagram shows everything something can be, and what moves it from one to the next:

- States are rounded boxes:
ordered,shipped,out for delivery,delivered,returned,canceled. - Events label the arrows: the thing that happens that moves the package.
shiptakes it fromorderedtoshipped. - The start dot, a solid black circle, points at the state everything starts in.
- No arrow means "not from here". There's one
cancelarrow, and it leavesordered. So canceling a package that'sout for deliveryisn't a rule you have to remember; it's an arrow that isn't there.
Textbooks call this a state machine diagram, and mark a state where the story ends (returned, canceled) with a bullseye, a dot inside a ring. Read it aloud and it's the rules list: "an ordered package can ship or cancel; a shipped package can load…". The bug above is visible at a glance: the code allowed an arrow the diagram doesn't have.
The fix: give each status its own class
Turn each box into a class. Each status class answers one question for every event: where does this lead from here? A status that allows an event returns the next status; one that doesn't returns nothing. The package keeps its current status and hands every request to it:

The fence is around the statuses, because the statuses are what change. Package is outside it: it never checks a status word again.
How it got its name
Letting an object change what it does when its inner state changes, by handing each request to an object for its current state, is the State pattern. Teams building order systems, games, network connections and document workflows kept writing the same if (status == …) checks, kept getting bitten by the one they missed, and kept landing on this fix, so it was written down and named in the original 1994 book. The pattern is its state diagram: each box becomes a class, each arrow a method that returns the next box.
The classic version
The same day for package 42, with one class per state:
Package parcel = new Package(42);
Console.WriteLine(parcel.Ship());
Console.WriteLine(parcel.Cancel());
Console.WriteLine(parcel.Load());
Console.WriteLine(parcel.Cancel());
Console.WriteLine(parcel.DropOff());
Console.WriteLine(parcel.ReturnPackage());
class Package
{
private PackageStatus status = new Ordered();
public int Id { get; }
public Package(int id) { Id = id; }
// The package asks its current status where each request leads.
public string Ship() => Move("ship", status.Ship());
public string Load() => Move("load", status.Load());
public string DropOff() => Move("drop off", status.DropOff());
public string ReturnPackage() => Move("return", status.ReturnPackage());
public string Cancel() => Move("cancel", status.Cancel());
private string Move(string action, PackageStatus? next)
{
if (next == null) { return quot;Package {Id}: can't {action}, it's {status.Name}"; }
status = next;
return quot;Package {Id}: {status.Name}";
}
}
// Each status answers: where does this lead from here? null means "not from here".
abstract class PackageStatus
{
public abstract string Name { get; }
public virtual PackageStatus? Ship() => null;
public virtual PackageStatus? Load() => null;
public virtual PackageStatus? DropOff() => null;
public virtual PackageStatus? ReturnPackage() => null;
public virtual PackageStatus? Cancel() => null;
}
class Ordered : PackageStatus
{
public override string Name => "ordered";
public override PackageStatus? Ship() => new Shipped();
public override PackageStatus? Cancel() => new Canceled();
}
class Shipped : PackageStatus
{
public override string Name => "shipped";
public override PackageStatus? Load() => new OutForDelivery();
}
class OutForDelivery : PackageStatus
{
public override string Name => "out for delivery";
public override PackageStatus? DropOff() => new Delivered();
}
class Delivered : PackageStatus
{
public override string Name => "delivered";
public override PackageStatus? ReturnPackage() => new Returned();
}
class Returned : PackageStatus { public override string Name => "returned"; }
class Canceled : PackageStatus { public override string Name => "canceled"; }
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
// Each status answers: where does this lead from here? null means "not from here".
abstract class PackageStatus {
abstract String name();
PackageStatus ship() { return null; }
PackageStatus load() { return null; }
PackageStatus dropOff() { return null; }
PackageStatus returnPackage() { return null; }
PackageStatus cancel() { return null; }
}
class Ordered extends PackageStatus {
String name() { return "ordered"; }
PackageStatus ship() { return new Shipped(); }
PackageStatus cancel() { return new Canceled(); }
}
class Shipped extends PackageStatus {
String name() { return "shipped"; }
PackageStatus load() { return new OutForDelivery(); }
}
class OutForDelivery extends PackageStatus {
String name() { return "out for delivery"; }
PackageStatus dropOff() { return new Delivered(); }
}
class Delivered extends PackageStatus {
String name() { return "delivered"; }
PackageStatus returnPackage() { return new Returned(); }
}
class Returned extends PackageStatus { String name() { return "returned"; } }
class Canceled extends PackageStatus { String name() { return "canceled"; } }
class Package {
int id;
PackageStatus status = new Ordered();
Package(int id) { this.id = id; }
// The package asks its current status where each request leads.
String ship() { return move("ship", status.ship()); }
String load() { return move("load", status.load()); }
String dropOff() { return move("drop off", status.dropOff()); }
String returnPackage() { return move("return", status.returnPackage()); }
String cancel() { return move("cancel", status.cancel()); }
String move(String action, PackageStatus next) {
if (next == null) { return "Package " + id + ": can't " + action + ", it's " + status.name(); }
status = next;
return "Package " + id + ": " + status.name();
}
}
void main() {
Package parcel = new Package(42);
IO.println(parcel.ship());
IO.println(parcel.cancel());
IO.println(parcel.load());
IO.println(parcel.cancel());
IO.println(parcel.dropOff());
IO.println(parcel.returnPackage());
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
class PackageStatus:
"""Each status answers: where does this lead from here? None means "not from here"."""
name = ""
def ship(self):
return None
def load(self):
return None
def drop_off(self):
return None
def return_package(self):
return None
def cancel(self):
return None
class Ordered(PackageStatus):
name = "ordered"
def ship(self):
return Shipped()
def cancel(self):
return Canceled()
class Shipped(PackageStatus):
name = "shipped"
def load(self):
return OutForDelivery()
class OutForDelivery(PackageStatus):
name = "out for delivery"
def drop_off(self):
return Delivered()
class Delivered(PackageStatus):
name = "delivered"
def return_package(self):
return Returned()
class Returned(PackageStatus):
name = "returned"
class Canceled(PackageStatus):
name = "canceled"
class Package:
def __init__(self, id):
self.id = id
self.status = Ordered()
# The package asks its current status where each request leads.
def ship(self):
return self._move("ship", self.status.ship())
def load(self):
return self._move("load", self.status.load())
def drop_off(self):
return self._move("drop off", self.status.drop_off())
def return_package(self):
return self._move("return", self.status.return_package())
def cancel(self):
return self._move("cancel", self.status.cancel())
def _move(self, action, next_status):
if next_status is None:
return f"Package {self.id}: can't {action}, it's {self.status.name}"
self.status = next_status
return f"Package {self.id}: {self.status.name}"
parcel = Package(42)
print(parcel.ship())
print(parcel.cancel())
print(parcel.load())
print(parcel.cancel())
print(parcel.drop_off())
print(parcel.return_package())
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
// Each status answers: where does this lead from here? null means "not from here".
class PackageStatus {
ship() { return null; }
load() { return null; }
dropOff() { return null; }
returnPackage() { return null; }
cancel() { return null; }
}
class Ordered extends PackageStatus {
name = "ordered";
ship() { return new Shipped(); }
cancel() { return new Canceled(); }
}
class Shipped extends PackageStatus {
name = "shipped";
load() { return new OutForDelivery(); }
}
class OutForDelivery extends PackageStatus {
name = "out for delivery";
dropOff() { return new Delivered(); }
}
class Delivered extends PackageStatus {
name = "delivered";
returnPackage() { return new Returned(); }
}
class Returned extends PackageStatus { name = "returned"; }
class Canceled extends PackageStatus { name = "canceled"; }
class Package {
status = new Ordered();
constructor(id) {
this.id = id;
}
// The package asks its current status where each request leads.
ship() { return this.move("ship", this.status.ship()); }
load() { return this.move("load", this.status.load()); }
dropOff() { return this.move("drop off", this.status.dropOff()); }
returnPackage() { return this.move("return", this.status.returnPackage()); }
cancel() { return this.move("cancel", this.status.cancel()); }
move(action, next) {
if (next === null) { return `Package ${this.id}: can't ${action}, it's ${this.status.name}`; }
this.status = next;
return `Package ${this.id}: ${this.status.name}`;
}
}
const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.cancel());
console.log(parcel.load());
console.log(parcel.cancel());
console.log(parcel.dropOff());
console.log(parcel.returnPackage());
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
// Each status answers: where does this lead from here? null means "not from here".
abstract class PackageStatus {
abstract name: string;
ship(): PackageStatus | null { return null; }
load(): PackageStatus | null { return null; }
dropOff(): PackageStatus | null { return null; }
returnPackage(): PackageStatus | null { return null; }
cancel(): PackageStatus | null { return null; }
}
class Ordered extends PackageStatus {
name = "ordered";
ship(): PackageStatus { return new Shipped(); }
cancel(): PackageStatus { return new Canceled(); }
}
class Shipped extends PackageStatus {
name = "shipped";
load(): PackageStatus { return new OutForDelivery(); }
}
class OutForDelivery extends PackageStatus {
name = "out for delivery";
dropOff(): PackageStatus { return new Delivered(); }
}
class Delivered extends PackageStatus {
name = "delivered";
returnPackage(): PackageStatus { return new Returned(); }
}
class Returned extends PackageStatus { name = "returned"; }
class Canceled extends PackageStatus { name = "canceled"; }
class Package {
id: number;
status: PackageStatus = new Ordered();
constructor(id: number) {
this.id = id;
}
// The package asks its current status where each request leads.
ship(): string { return this.move("ship", this.status.ship()); }
load(): string { return this.move("load", this.status.load()); }
dropOff(): string { return this.move("drop off", this.status.dropOff()); }
returnPackage(): string { return this.move("return", this.status.returnPackage()); }
cancel(): string { return this.move("cancel", this.status.cancel()); }
move(action: string, next: PackageStatus | null): string {
if (next === null) { return `Package ${this.id}: can't ${action}, it's ${this.status.name}`; }
this.status = next;
return `Package ${this.id}: ${this.status.name}`;
}
}
const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.cancel());
console.log(parcel.load());
console.log(parcel.cancel());
console.log(parcel.dropOff());
console.log(parcel.returnPackage());
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
The fourth line is right now: OutForDelivery has no Cancel, so it falls back to the base class's "not from here", exactly as the diagram has no arrow. Read the status classes from top to bottom and they're the diagram, one box at a time. And held at the depot will be one new class, HeldAtDepot, plus one changed line in Shipped (its new arrow out). Ordered, Delivered and the rest can't break, because nobody opens them.
Where the languages differ. C#, Java and TypeScript mark the base class abstract, so nobody makes a status with no name. Python and JavaScript give the base class the "not from here" answers and let each subclass set its name. C# and TypeScript write the "maybe nothing" answer as PackageStatus? and PackageStatus | null.
Here is the drop-off as a sequence diagram: the package doesn't decide; it asks.

The modern version: the diagram as data
Here, each status only decides where each event leads. When that's all it decides, the whole diagram fits in a table of moves: for each status, which events it allows and where each one goes. The package looks its move up instead of asking an object:
Package parcel = new Package(42);
foreach (string action in new List<string> { "ship", "cancel", "load", "cancel", "drop off", "return" })
{
Console.WriteLine(parcel.Perform(action));
}
class Package
{
// The state diagram as data: for each status, where each allowed action leads.
private static readonly Dictionary<string, Dictionary<string, string>> Moves = new Dictionary<string, Dictionary<string, string>>
{
["ordered"] = new Dictionary<string, string> { ["ship"] = "shipped", ["cancel"] = "canceled" },
["shipped"] = new Dictionary<string, string> { ["load"] = "out for delivery" },
["out for delivery"] = new Dictionary<string, string> { ["drop off"] = "delivered" },
["delivered"] = new Dictionary<string, string> { ["return"] = "returned" },
["returned"] = new Dictionary<string, string>(),
["canceled"] = new Dictionary<string, string>()
};
public int Id { get; }
public string Status { get; private set; } = "ordered";
public Package(int id) { Id = id; }
public string Perform(string action)
{
if (!Moves[Status].TryGetValue(action, out string? next))
{
return quot;Package {Id}: can't {action}, it's {Status}";
}
Status = next;
return quot;Package {Id}: {Status}";
}
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
class Package {
// The state diagram as data: for each status, where each allowed action leads.
static final Map<String, Map<String, String>> MOVES = Map.of(
"ordered", Map.of("ship", "shipped", "cancel", "canceled"),
"shipped", Map.of("load", "out for delivery"),
"out for delivery", Map.of("drop off", "delivered"),
"delivered", Map.of("return", "returned"),
"returned", Map.of(),
"canceled", Map.of());
int id;
String status = "ordered";
Package(int id) { this.id = id; }
String perform(String action) {
String next = MOVES.get(status).get(action);
if (next == null) { return "Package " + id + ": can't " + action + ", it's " + status; }
status = next;
return "Package " + id + ": " + status;
}
}
void main() {
Package parcel = new Package(42);
for (String action : List.of("ship", "cancel", "load", "cancel", "drop off", "return")) {
IO.println(parcel.perform(action));
}
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
# The state diagram as data: for each status, where each allowed action leads.
MOVES = {
"ordered": {"ship": "shipped", "cancel": "canceled"},
"shipped": {"load": "out for delivery"},
"out for delivery": {"drop off": "delivered"},
"delivered": {"return": "returned"},
"returned": {},
"canceled": {},
}
class Package:
def __init__(self, id):
self.id = id
self.status = "ordered"
def perform(self, action):
next_status = MOVES[self.status].get(action)
if next_status is None:
return f"Package {self.id}: can't {action}, it's {self.status}"
self.status = next_status
return f"Package {self.id}: {self.status}"
parcel = Package(42)
for action in ["ship", "cancel", "load", "cancel", "drop off", "return"]:
print(parcel.perform(action))
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
// The state diagram as data: for each status, where each allowed action leads.
const moves = new Map([
["ordered", new Map([["ship", "shipped"], ["cancel", "canceled"]])],
["shipped", new Map([["load", "out for delivery"]])],
["out for delivery", new Map([["drop off", "delivered"]])],
["delivered", new Map([["return", "returned"]])],
["returned", new Map()],
["canceled", new Map()],
]);
class Package {
status = "ordered";
constructor(id) {
this.id = id;
}
perform(action) {
const next = moves.get(this.status).get(action);
if (next === undefined) { return `Package ${this.id}: can't ${action}, it's ${this.status}`; }
this.status = next;
return `Package ${this.id}: ${this.status}`;
}
}
const parcel = new Package(42);
for (const action of ["ship", "cancel", "load", "cancel", "drop off", "return"]) {
console.log(parcel.perform(action));
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
// The state diagram as data: for each status, where each allowed action leads.
const moves = new Map<string, Map<string, string>>([
["ordered", new Map([["ship", "shipped"], ["cancel", "canceled"]])],
["shipped", new Map([["load", "out for delivery"]])],
["out for delivery", new Map([["drop off", "delivered"]])],
["delivered", new Map([["return", "returned"]])],
["returned", new Map()],
["canceled", new Map()],
]);
class Package {
id: number;
status = "ordered";
constructor(id: number) {
this.id = id;
}
perform(action: string): string {
const next = moves.get(this.status)!.get(action);
if (next === undefined) { return `Package ${this.id}: can't ${action}, it's ${this.status}`; }
this.status = next;
return `Package ${this.id}: ${this.status}`;
}
}
const parcel = new Package(42);
for (const action of ["ship", "cancel", "load", "cancel", "drop off", "return"]) {
console.log(parcel.perform(action));
}
Package 42: shipped
Package 42: can't cancel, it's shipped
Package 42: out for delivery
Package 42: can't cancel, it's out for delivery
Package 42: delivered
Package 42: returned
Same six lines. The table is the diagram you drew, almost word for word, and a new status is one new row. This is how many state-machine libraries work, and it's often all an app needs.
The classes win back their place the moment each status has more to do than pick the next one: a held package that texts its customer each morning, a delivered one that starts a 30-day return window, a different message on the website for each. Then each status has behavior of its own, and a class is where behavior lives.
Where you've already used it
- A JavaScript
Promiseispending, thenfulfilledorrejected, andthenbehaves differently in each: it waits, runs your function, or skips it. - A pull request on GitHub is a draft, open, merged or closed, and which buttons you see depends on which.
- A checkout page's Pay button is idle, sending or done, and it does nothing while it's sending, so a double click doesn't charge twice.
When not to use it
- Two states and one rule. A light that's on or off, or a field that's
isPaid, reads fine as abooland anif. - When the status changes only a label, not what the object can do. A word, or an enum, is enough.
- When the table of moves says it all. If no status has behavior of its own, the table is shorter and easier to check than six classes.
The cost: a class for every status, so seeing all the rules means opening several files. The state diagram is the map that makes that quick; keep it beside the code.
Look-alike: on paper, State looks like Strategy (an object handing work to another it holds). The difference is who picks: you hand a strategy in, but a state picks the next state itself. Look-Alikes: Strategy, State and Command puts them side by side.
How often you'll meet it: now and then (our estimate: as a hand-written pattern in order, booking and game code; as a table or a library much more often).
Check yourself
2 questions to try on the lesson page.
So what
When every method asks "what's my status?", draw the state diagram, then give each box its own class. The rules for each status live in one place, the bug from the missing check can't happen, and a new status is one new class.