Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Model a payment result as an algebraic data type in Java 25 with success, declined with a reason, and failed with an exception, and show how callers consume it.

We model the result as a sealed interface with three record implementations: sealed interface PaymentResult permits Approved, Declined, Failed {}, with record Approved(String txId), record Declined(String reason) and record Failed(Exception cause). Callers consume it with a switch using record patterns, case Approved(var id) -> ..., and the compiler checks that all three outcomes are handled without a default. The sealed interface is a sum type, the records are product types, and expected outcomes become part of the method's type instead of hiding in exceptions.

Why this question is asked

A payment call has more than one normal outcome. A card can be approved, declined for a business reason, or the call can fail because a provider is down. Code that returns a boolean or throws an exception for a decline tends to lose information or mix business outcomes with technical failures. Interviewers ask this design question to see whether we can use Java 25's sealed types and records to make the outcomes explicit, and whether we understand the vocabulary behind it. In this answer, we will recap algebraic data types, write the model, show how callers consume it, explain what the compiler checks, and compare the design with exceptions.

1A Quick Recap of Algebraic Data Types

An algebraic data type, often shortened to ADT, is a type built from two kinds of combination. A product type groups several values together: a record with a txId and an amount has one value of each, so its possible values are the product of its components' possibilities. A sum type is a choice between alternatives: a value is one of several shapes, and the total number of possibilities is the sum of the alternatives.

Java 25 has both. Records are product types: record Declined(String reason) is a named group of components. Sealed interfaces are sum types: sealed interface PaymentResult permits Approved, Declined, Failed says a PaymentResult is exactly one of these three, and no other class may implement it.

2Writing the Model

Here is the whole model. Each record carries only what its outcome needs, and the compact constructors reject impossible states at creation time.

Java
public sealed interface PaymentResult permits Approved, Declined, Failed {}
public record Approved(String txId) implements PaymentResult {
public Approved { Objects.requireNonNull(txId); }
}
public record Declined(String reason) implements PaymentResult {
public Declined { Objects.requireNonNull(reason); }
}
public record Failed(Exception cause) implements PaymentResult {
public Failed { Objects.requireNonNull(cause); }
}
interface PaymentGateway {
PaymentResult charge(String cardToken, long amountCents);
}
The three outcomes
RecordCarriesMeaning
Approved(txId)the provider's transaction idmoney moved; store the id for refunds
Declined(reason)a business reason such as insufficient fundsexpected outcome; tell the customer
Failed(cause)the technical exceptionunknown state; retry or reconcile
A sum of three product types: a PaymentResult is exactly one row.

Notice what the signature now tells a caller: charge returns one of three outcomes, and the type says which ones. Records are implicitly final, which satisfies the rule that every permitted subtype of a sealed type must be final, sealed or non-sealed. If the records are declared in the same source file as the interface, the permits clause can even be left out and the compiler infers it from that file, though writing it is clearer in an API.

3Consuming the Result in a Switch

Callers use a switch with record patterns. Each case deconstructs the record and binds its component.

Java
String checkoutMessage(PaymentResult result) {
return switch (result) {
case Approved(var id) -> "Paid. Reference " + id;
case Declined(var r) -> "Card declined: " + r;
case Failed(var e) -> "We could not reach the bank, please try again";
};
}
checkoutMessage(new Approved("tx-981")); // Paid. Reference tx-981
checkoutMessage(new Declined("insufficient funds")); // Card declined: insufficient funds
checkoutMessage(new Failed(new IOException("timeout"))); // We could not reach the bank, please try again

There is no default branch. That is intentional and is the main benefit of the model: the switch is exhaustive because the compiler knows the three permitted types. If we later add a fourth outcome, such as record PendingReview(String caseId), every switch over PaymentResult stops compiling until it decides what to do with a pending review. With a default, the new outcome would silently be treated like whatever the default did.

4What the Compiler Checks for Us

Because PaymentResult is sealed, javac reads its permits list and verifies that the cases cover Approved, Declined and Failed. A guarded case, such as case Declined(var r) when r.contains("fraud"), does not count toward coverage on its own, so we still need an unguarded Declined case after it. The compiler also inserts a hidden default that throws MatchException, which would only fire if a separately compiled version of the library added a permitted type our code has never seen.

This gives us something exceptions cannot: the compiler proves that every caller has a decision for every outcome. With exceptions, nothing forces a caller to handle a decline differently from a timeout, and unchecked exceptions do not even appear in the signature.

5Compared With Exceptions

A common older design is boolean charge() that throws CardDeclinedException for declines and IOException for failures. That mixes two very different things. A decline is an expected business outcome that happens many times a day; a timeout is a technical failure that leaves us unsure whether money moved. Exceptions are best for the unexpected, and using them for routine outcomes makes the normal path look like an error path and is easy to forget to handle.

With the sealed result, the expected outcomes are part of the type, and callers see them in the signature and in the switch. We still keep exceptions for truly unexpected problems, such as a programming error, and the Failed record is where an expected technical failure from the provider is reported, with its cause preserved for logging. The result is a design where reading one method signature tells us everything a caller must handle.

Step throughCheckout consuming a payment result
CheckoutPaymentGatewayProvider
charge(token, 4999)
authorize
declined: insufficient funds
Declined("insufficient funds")
switch: case Declined(var r) -> show message

5 messages in order. Play them, or step through them one at a time.

The decline travels as a value, not as an exception.

6Follow-up questions

Why not use Optional or a boolean?

Because there are three distinct outcomes with different data. Optional can say present or absent, and a boolean can say yes or no, but neither can carry a transaction id in one case, a reason in another and an exception in the third. The sealed interface keeps each outcome's data with it.

How do we serialize this to JSON for an API?

Jackson needs to know which record a JSON object represents. We add @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") on the interface and @JsonSubTypes listing the three records with their names. The allow-list of names also prevents arbitrary class names from being deserialized.

Should Failed hold an Exception or something simpler?

Holding the Exception keeps the stack trace for logs, which is useful inside a service. At an API boundary we would map it to a simple error code and message rather than expose exception details to clients.

7Conclusion

In this answer, we modelled a payment result as an algebraic data type: a sealed interface PaymentResult, the sum type, permitting three records, the product types, Approved(txId), Declined(reason) and Failed(cause). Callers consume it with a switch using record patterns and no default, and the compiler checks that every outcome is handled, so adding an outcome finds every caller. Compared with exceptions, the design makes expected business outcomes part of the method's type and keeps exceptions for the unexpected.

What to say in the interviewAbout 80 seconds aloud

Open with

I would model it as a sealed interface with three records. sealed interface PaymentResult permits Approved, Declined, Failed, then record Approved(String txId), record Declined(String reason) and record Failed(Exception cause), each implementing the interface, with compact constructors that reject nulls.

Then, if they want more

The gateway method returns PaymentResult. Callers consume it with a switch using record patterns: case Approved(var id), case Declined(var r), case Failed(var e), each returning or doing what that outcome needs. There is no default on purpose.

Because the interface is sealed, the compiler knows these are the only three implementations and checks that the switch handles all of them, so if we later add something like PendingReview, every switch fails to compile until it handles it.

In type theory terms, the sealed interface is a sum type, a value is one of the alternatives, and each record is a product type, a group of components. The main reason I prefer this over exceptions is that a decline is an expected business outcome, not an error.

If I throw CardDeclinedException, nothing forces callers to handle it, and it mixes routine declines with real technical failures. With the sealed result, every expected outcome is visible in the signature and the compiler makes sure each caller has a decision for it.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Model a payment result as an algebraic data type in Java 25 with success, declined with...": https://scrivio-interview-library.netlify.app/java/sealed-and-pattern-matching/655160e9d7/