Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Strategy and Template Method in Java and Spring: From an SLA if-Ladder to Policy Beans, a Lambda Map, a Sealed Switch and an Import Skeleton
  • The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
  • When Not to Use a Design Pattern: Five Java Smells, the Patterns the Language Replaced, and a One-Page ADR for Saying No
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Programming

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

The ticket lifecycle. Open goes to Pending by assign. Pending goes to Resolved by resolve. Resolved goes to Closed by close, or to Reopened by reopen. Closed goes to Reopened by reopen. Reopened goes back to Resolved by resolve. Six arrows, six legal moves. There is no arrow from Open to Closed. OpenPendingResolvedClosedReopened assignresolveclose reopenreopenresolve no close() on Open
The arrows are the methods. A missing arrow is a missing method.

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 recordsSpring Statemachine
An illegal moveDoes not compile, or is refused in one switchThe event is not accepted at run time
SetupFive records, no extra libraryA library and a configuration class for states, events and transitions
What it addsNothing beyond what you writeGuards, actions, listeners, nested and parallel states, persisted machines
Pick it forA handful of states with simple rulesLong 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.

Keep going in Java · 46 of 82

Previous
Strategy and Template Method in Java and Spring: From an SLA if-Ladder to Policy Beans, a Lambda Map, a Sealed Switch and an Import Skeleton
Next post
When Not to Use a Design Pattern: Five Java Smells, the Patterns the Language Replaced, and a One-Page ADR for Saying No
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A status string, checked everywhere
  • The lifecycle as a map
  • Five states, a closed list
  • Events from outside go through one switch
  • A table that tests every move
  • Sealed records or Spring Statemachine?
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.