The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
Five services check a status string eight times, and one forgets a rule: T-8 is closed with nobody assigned and reopened with agent null. Five sealed records fix it. Each legal move is a method on the state it leaves, so new Open("T-8").close() does not compile. One switch handles events from outside, and 20 tests cover 6 legal moves and 14 refusals.
What you will learn
- Spot the bug that status strings checked in many services invite
- Model each state as a record in a sealed interface, with each legal move as a method on the state it leaves
- Route run-time events through one pattern-matching switch with guards
- Test every state against every event with a 20-row parameterized table, and know when Spring Statemachine is worth it
Before you start
- Java records
- Sealed interfaces and pattern matching for switch
- JUnit 5 basics
A support ticket moves through a life: open, pending with an agent, resolved, closed, sometimes reopened. The rules say which moves are allowed from where. This article shows what goes wrong when those rules live in status strings spread across services, then rebuilds the lifecycle so the Java type system enforces them.
A status string, checked everywhere
// The status is a string, and every service checks it its own way.
class Ticket {
String id;
String status = "OPEN";
String agent;
...
}
class AssignService {
String assign(Ticket t, String agent) {
if (!t.status.equals("OPEN") && !t.status.equals("REOPENED")) return "refused";
t.agent = agent;
t.status = "PENDING";
return "ok";
}
}
class CloseService {
String close(Ticket t) {
if (t.status.equals("CLOSED")) return "refused"; // forgot: unassigned, not resolved
t.status = "CLOSED";
return "ok";
}
}
There are five services like this, with eight status checks between them. Each checks for itself, and the close service forgot a rule:
assign T-7 to Grace: ok, PENDING
resolve T-7: ok, RESOLVED
close T-8, nobody assigned: ok, CLOSED
reopen T-8: ok, agent null
T-8 was closed with nobody assigned and then reopened with no agent. A typo like "Closed" in one service would compile fine too, and silently let a ticket through.
The lifecycle as a map
Five states, a closed list
// Every state a ticket can be in. The compiler knows the full list.
public sealed interface TicketState permits Open, Pending, Resolved, Closed, Reopened {
String id();
default String label() {
return getClass().getSimpleName();
}
}
Only these five types can be a ticket state, and each is a record in its own file. There is no status string left to mistype. Each legal move is a method on the state it leaves, returning the state it enters:
// New and unassigned. The only way forward is to give it an agent.
public record Open(String id) implements TicketState {
public Pending assign(String agent) {
return new Pending(id, agent);
}
}
// Assigned, being worked on. Every later state carries the agent.
public record Pending(String id, String agent) implements TicketState {
public Resolved resolve(String note) {
return new Resolved(id, agent, note);
}
}
// Fixed, waiting for the customer: close it, or reopen it.
public record Resolved(String id, String agent, String note) implements TicketState {
public Closed close() {
return new Closed(id, agent);
}
public Reopened reopen(String reason) {
return new Reopened(id, agent, reason);
}
}
Closed has reopen, and Reopened has resolve, which makes six moves in total, each written once. Open has no agent field, because an open ticket is unassigned by definition. Write new Open("T-8").close() and javac answers cannot find symbol: method close(). No if statement decides that.
Open open = new Open("T-7");
Pending pending = open.assign("Grace");
Resolved resolved = pending.resolve("password reset");
Closed closed = resolved.close();
Reopened reopened = closed.reopen("still locked out");
Closed again = reopened.resolve("account unlocked").close();
Open[id=T-7]
Pending[id=T-7, agent=Grace]
Resolved[id=T-7, agent=Grace, note=password reset]
Closed[id=T-7, agent=Grace]
Reopened[id=T-7, agent=Grace, reason=still locked out]
Closed[id=T-7, agent=Grace]
Events from outside go through one switch
Typed calls work inside the code. A button or a REST call, though, sends an event at run time, and the compiler cannot check that. One switch routes each event to the state that can take it:
public enum Event {
ASSIGN, RESOLVE, CLOSE, REOPEN
}
public static TicketState on(TicketState state, Event event, String detail) {
return switch (state) {
case Open open when event == Event.ASSIGN -> open.assign(detail);
case Pending pending when event == Event.RESOLVE -> pending.resolve(detail);
case Resolved resolved when event == Event.CLOSE -> resolved.close();
case Resolved resolved when event == Event.REOPEN -> resolved.reopen(detail);
case Closed closed when event == Event.REOPEN -> closed.reopen(detail);
case Reopened reopened when event == Event.RESOLVE -> reopened.resolve(detail);
default -> throw new IllegalStateException(
event + " is not allowed from " + state.label());
};
}
Six cases for six legal moves, and each case calls the method on the state, so no rule is copied. Everything else is refused in one place with one message:
T-8: CLOSE is not allowed from Open
Type patterns with when guards are explained in pattern matching for instanceof and switch.
A table that tests every move
// Every state against every event: 6 legal moves, 14 refusals.
@ParameterizedTest(name = "{0} + {1} -> {2}")
@CsvSource({
"Open, ASSIGN, Pending", "Open, RESOLVE, refused",
"Open, CLOSE, refused", "Open, REOPEN, refused",
"Pending, ASSIGN, refused", "Pending, RESOLVE, Resolved",
...
"Reopened, CLOSE, refused", "Reopened, REOPEN, refused",
})
void everyTransition(String from, Event event, String expected) {
TicketState state = START.get(from);
if (expected.equals("refused")) {
assertThrows(IllegalStateException.class, () -> Lifecycle.on(state, event, "x"));
} else {
assertEquals(expected, Lifecycle.on(state, event, "x").label());
}
}
[INFO] Tests run: 20, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.372 s -- in org.studyeasy.s03l04.state.LifecycleTest
Five states times four events is 20 rows, and a refusal is a test too. Add a state or an event and the table shows exactly which rows are new.
Sealed records or Spring Statemachine?
| Sealed records | Spring Statemachine | |
|---|---|---|
| An illegal move | Does not compile, or is refused in one switch | The event is not accepted at run time |
| Setup | Five records, no extra library | A library and a configuration class for states, events and transitions |
| What it adds | Nothing beyond what you write | Guards, actions, listeners, nested and parallel states, persisted machines |
| Pick it for | A handful of states with simple rules | Long workflows with many states, timers or actions on each move |
For five states, the type system is the state machine. Reach for the library when the workflow outgrows a switch. And sometimes the honest answer is no pattern at all, which is the subject of when not to use a pattern.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
