Making Illegal Payment States Unrepresentable
Sealed interfaces, records and pattern matching
Sealed interfaces, records and pattern matching
Almost every payment system has a class that looks like this: a Payment entity with a PaymentStatus enum and a dozen nullable fields, such as authCode, authorisedAt, capturedAmount, settledAt, declineReason and voidedAt. Which of those fields are filled in is supposed to depend on the status. Nothing enforces it. Somewhere in the service layer, a chain of if (payment.getStatus() == AUTHORISED) checks decides what can happen next, and every developer who touches the code has to remember the rules.
Most of the time that works. Then a refund path calls setStatus(CAPTURED) on a payment that was never authorised, or a batch job settles a voided payment, or a captured amount ends up larger than the authorised one. Each of these is a valid combination of fields as far as the compiler is concerned, and each is a state the business says is impossible. They're found in reconciliation, in a customer complaint or in an audit, rarely in a code review.
Modern Java offers a better arrangement. With sealed interfaces and records, each payment state becomes its own type carrying exactly the data that state needs, and transitions become methods that exist only on the states where they're allowed. The compiler then rejects whole categories of bugs that tests and reviews currently have to catch. This article shows how to model that on a Java 17 baseline, what Java 21 adds, and how to move an existing enum-and-nullable-fields codebase towards it without a rewrite.
One type per state, with only the data that state needs
The first step is to stop modelling "a payment with a status" and start modelling "a payment that is in exactly one of these states". A sealed interface declares the complete set:
1 public sealed interface Payment
2 permits Initiated, Authorised, Declined, Captured, Settled, Voided {
3 PaymentId id();
4 Money amount();
5 }
permits is the important word. No other class, in this module or anywhere else, can implement Payment. The list of states is closed and known to the compiler. Each state is then a record holding precisely the fields that exist in that state:
1 public record Initiated(PaymentId id, Money amount, AccountRef debtor,
2 Instant createdAt) implements Payment {}
3
4 public record Authorised(PaymentId id, Money amount, AccountRef debtor,
5 AuthCode authCode, Instant authorisedAt) implements Payment {
6 public Authorised {
7 Objects.requireNonNull(authCode, "an authorised payment must have an auth code");
8 Objects.requireNonNull(authorisedAt, "an authorised payment must have a timestamp");
9 }
10 }
11 public record Captured(PaymentId id, Money amount, Money authorisedAmount,
12 AuthCode authCode, Instant capturedAt) implements Payment {
13 public Captured {
14 if (amount.isGreaterThan(authorisedAmount))
15 throw new IllegalArgumentException("captured amount exceeds authorised amount");
16 }
17 }
Several bugs have already disappeared. An Initiated payment has no authCode field, so code can't read one that doesn't exist yet. An Authorised payment can't be constructed without an auth code, because the compact constructor rejects it. A Captured payment can't carry a captured amount larger than what was authorised. The invariants live in one place, the type that owns them, rather than being repeated or forgotten across service classes. And because records are immutable, a state can't be half-changed by a setter called halfway through a method.
The second step is to put each transition on the state it starts from, and to return the state it leads to:
1 public record Initiated(...) implements Payment {
2 public Authorised authorise(AuthCode code, Instant at) {
3 return new Authorised(id, amount, debtor, code, at);
4 }
5 public Declined decline(DeclineReason reason, Instant at) {
6 return new Declined(id, amount, reason, at);
7 }
8 }
9 public record Authorised(...) implements Payment {
10 public Captured capture(Money captureAmount, Instant at) {
11 return new Captured(id, captureAmount, amount, authCode, at);
12 }
13 public Voided voidAuthorisation(Instant at) {
14 return new Voided(id, amount, at);
15 }
16 }
Now the state machine is the type system. Calling capture on an Initiated payment isn't a runtime error that a test might catch. It's a compile error, because Initiated has no capture method. Settling a Voided payment can't be written. A partial capture that exceeds the authorisation fails at the moment of construction, with a message that names the rule. The allowed transitions can be read directly from the code: open each record and look at its methods. That makes the model something a business analyst can review with the developer, not just something the developer has to keep in their head.
Plenty of code needs to deal with a payment in whatever state it's in: building a customer-facing status message, mapping to an API response, deciding what the operations dashboard shows. The risk is the same in every codebase. Someone adds a new state, such as PartiallyRefunded, and the places that should handle it silently fall into a default branch.
On Java 21 and later, pattern matching for switch over a sealed type solves this directly:
1 String customerStatus(Payment payment) {
2 return switch (payment) {
3 case Initiated i -> "Processing";
4 case Authorised a -> "Approved, completing shortly";
5 case Declined d -> "Declined: " + d.reason().customerText();
6 case Captured c -> "Completed";
7 case Settled s -> "Completed";
8 case Voided v -> "Cancelled";
9 };
10 }
There's no default branch, and that's deliberate. Because Payment is sealed, the compiler knows the switch is exhaustive. When PartiallyRefunded is added to the permits list, every switch like this one stops compiling until someone decides what it should do. Adding a default would switch that safety off, so a team rule worth adopting is that switches over sealed payment types never have one.
On a Java 17 baseline, where pattern matching for switch is still a preview feature, the same guarantee comes from declaring the behaviour on the sealed interface itself, so that every permitted record has to implement it:
1 public sealed interface Payment permits Initiated, Authorised, Declined,
2 Captured, Settled, Voided {
3 PaymentId id();
4 Money amount();
5 R accept(PaymentVisitor visitor);
6 }
7
8 public interface PaymentVisitor {
9 R initiated(Initiated p);
10 R authorised(Authorised p);
11 R declined(Declined p);
12 R captured(Captured p);
13 R settled(Settled p);
14 R voided(Voided p);
15 }
Each record implements accept with one line that calls its own visitor method. Adding a state means adding a visitor method, and every visitor in the codebase then fails to compile until it handles the new case. It's more verbose than a pattern-matching switch, but it gives the same compile-time guarantee on Java 17, and it converts mechanically to switch expressions when the platform moves to 21.
The sealed model is a domain model, and it needs a boundary with infrastructure that was built around the old shape.
Persistence. Records can't be JPA entities: JPA needs a no-argument constructor and mutable fields. Keep the existing entity, with its status column and nullable fields, as a persistence detail, and convert at the repository boundary. On Java 17, a switch expression over the status enum is checked for exhaustiveness by the compiler, so the mapper itself can't miss a state:
1 Payment toDomain(PaymentEntity e) {
2 return switch (e.getStatus()) {
3 case INITIATED -> new Initiated(e.id(), e.amount(), e.debtor(), e.getCreatedAt());
4 case AUTHORISED -> new Authorised(e.id(), e.amount(), e.debtor(),
5 e.getAuthCode(), e.getAuthorisedAt());
6 case CAPTURED -> new Captured(e.id(), e.getCapturedAmount(), e.amount(),
7 e.getAuthCode(), e.getCapturedAt());
8 case DECLINED -> new Declined(e.id(), e.amount(), e.getDeclineReason(), e.getDeclinedAt());
9 case SETTLED -> new Settled(e.id(), e.getCapturedAmount(), e.getSettledAt());
10 case VOIDED -> new Voided(e.id(), e.amount(), e.getVoidedAt());
11 };
12 }
When this mapper runs against years of production data, the compact constructors will find rows that break the rules: an authorised payment with no auth code, a capture larger than its authorisation. That's not a problem the new model created. It's a data quality problem the old model was hiding. Treat those rows as findings for the data owner, and decide case by case how to correct or quarantine them.
The database itself. Once the data is clean, the same invariants can be enforced in the schema. In PostgreSQL, add check constraints as NOT VALID first so they apply to new writes immediately, then VALIDATE them once the history has been corrected:
1 ALTER TABLE payment ADD CONSTRAINT authorised_payments_have_auth_code
2 CHECK (status NOT IN ('AUTHORISED', 'CAPTURED', 'SETTLED') OR auth_code IS NOT NULL)
3 NOT VALID;
4 -- after remediation of historical rows:
5 ALTER TABLE payment VALIDATE CONSTRAINT authorised_payments_have_auth_code;
Concurrent transitions. Immutable states don't stop two requests from transitioning the same payment at once, for example a capture and a void racing each other. That remains a job for the persistence layer: an optimistic-locking version column on the entity, so the second writer fails and retries against the new state.
APIs. Jackson serialises records natively from version 2.12, and sealed hierarchies work with @JsonTypeInfo and @JsonSubTypes. A type discriminator in the JSON makes each state's shape explicit for API consumers too. For example, a Declined payment carries a reason, and an Initiated payment never pretends to have one.
Few teams can stop and rewrite their payment model, and they shouldn't need to. The migration that works is incremental:
Recover the real state machine from data, not documentation. Query the audit or event history for the status transitions that actually occur in production. The result usually includes a few transitions nobody knew were happening. Each one is either a missing business rule or a bug.
Introduce the sealed model alongside the entity. Add the records and the repository mapper without changing callers. Run the mapper in a read-only check against production-like data to surface invalid rows early.
Move one use case at a time. Replace setStatus calls in a single flow, such as capture, with the transition method on the domain type, then persist the result. Each flow is a small, reviewable, separately releasable change.
Lock in progress. Add an architecture test, for example with ArchUnit, that forbids calling setStatus outside the mapper. Once the last caller is migrated, the old path can't creep back in.
Finish in the database. Add the check constraints, validate them, and the invariants are enforced at every layer.
None of this is clever code. It's the same discipline payment systems have always needed, written down where the compiler can check it: a closed list of states, the exact data each state carries, the transitions each state allows, and a guarantee that every place handling payments has considered every state. The bugs it removes are some of the most expensive in payments, because they often surface first in reconciliation or with a customer, long after the code that caused them shipped.
For a team on Java 17, almost all of it is available today. Java 21 makes the exhaustive handling more concise. And the move from an existing enum-and-nullable-fields model can happen one flow at a time, alongside normal delivery. That's how we prefer to approach payment domain models: design them so the wrong thing is hard to write in the first place.