Scrivio Interview library
ConceptPrincipal7 min read · updated 12 November 2026

Modern Java supports both object-oriented polymorphism and data-oriented pattern matching over sealed types. Explain the expression problem and how you would guide teams to choose between the two styles for long-lived domain code.

The expression problem says that object-oriented dispatch makes it easy to add new types but hard to add new operations, because each operation lives in every class, while pattern matching over a closed set of types makes new operations easy and new types hard, because each type appears in every switch. I guide teams to choose OO polymorphism where other teams or plugins add types, sealed types with pattern switches where one team owns the variants and operations change often, to mix the two only deliberately, and to write the decision rule down with examples from our own systems.

Why this question is asked

Java now gives us two mature ways to model a family of related types. The classic way is an interface with methods that each class overrides. The newer way, complete since Java 21, is a sealed interface of records with exhaustive switch expressions over them, often called data-oriented programming. Both are good, both are idiomatic, and teams that mix them at random end up with domain code that is hard to extend in either direction. Interviewers ask this at a senior level because the answer is a judgment about how code will change over years, not about syntax. In this answer, we will state the expression problem with a small example, look at what each style makes cheap and expensive, give a decision rule with examples, discuss mixing, and describe how to make the rule stick in an organization.

1A Quick Recap of the Two Styles

In the object-oriented style, the operations are methods on an interface, and each type implements them. A call such as event.apply(account) is dispatched at run time to the right class. In the data-oriented style, the types are plain data, usually records, the set of types is closed by a sealed interface, and each operation is a function with a switch that handles every type. Sealed means the interface names all its permitted implementations, so the compiler knows the complete list and can check that a switch is exhaustive.

Java
// Object-oriented: operations live inside the types
interface Event { void apply(Account a); String describe(); }
record Deposited(long cents) implements Event {
public void apply(Account a) { a.add(cents); }
public String describe() { return "deposit " + cents; }
}
// Data-oriented: types are data, operations are switches
sealed interface Event2 permits Deposited2, Withdrawn2 { }
record Deposited2(long cents) implements Event2 { }
record Withdrawn2(long cents) implements Event2 { }
static String describe(Event2 e) {
return switch (e) {
case Deposited2(long c) -> "deposit " + c;
case Withdrawn2(long c) -> "withdraw " + c;
}; // exhaustive: no default
}

2Stating the Expression Problem

Picture a grid. The rows are the types, deposit, withdrawal, fee, and the columns are the operations, apply, describe, toJson. Every cell needs code. The expression problem asks how we can add a new row or a new column without editing existing code, while keeping type safety. No mainstream design makes both directions free; each style picks one.

In the OO style, each row is a class holding its whole row of cells. Adding a type is one new class, and nobody else changes. But adding an operation means adding a method to the interface and then to every class, possibly in code owned by other teams. In the data-oriented style, each column is a function holding its whole column of cells. Adding an operation is one new function. But adding a type means editing every switch in the code base. The compensation is that the compiler lists every switch that lacks the new case, so nothing is missed, but the edits still touch many files.

What each style makes cheap
ChangeOO polymorphismSealed types + pattern switch
Add a new typeone new class, nothing else changesedit every switch; compiler lists them
Add a new operationedit the interface and every classone new function
Who can add typesanyone, even other modules or pluginsonly the owner of the sealed interface
Where a type's logic livestogether, in its classspread across operations
Where an operation livesspread across classestogether, in one switch

3The Decision Rule

The rule I give teams starts from one question: who adds variants, and how often, compared with operations? If other teams, customers' plugins or future modules add types, choose OO polymorphism. The interface is the extension point, and nobody should need to change our code to add a type. Examples from typical systems are payment providers behind a PaymentGateway, notification channels, exporters to file formats, and storage backends. The operations on them are few and stable, while the list of implementations grows.

If one team owns the full set of variants, and the variants change rarely while the things we do with them keep growing, choose sealed types and pattern switches. Examples are the events of an event-sourced aggregate, the states of an order, the nodes of a rules or pricing expression, and the result types of an operation, such as Success, Rejected and Failed. Here we keep adding operations, reporting, projections, validation, API mapping, and each one is clearest as a single switch that shows every case side by side. The compiler's exhaustiveness check turns every new variant into a precise to-do list.

Step throughChoosing a style for a family of types
  1. Do other teams or plugins add new types?
    YesInterface + polymorphismNoCheck what changes more
  2. Do operations change more often than variants?look at the change history
    YesSealed types + pattern switchesNoCheck behaviour per type
  3. Does each type carry substantial own behaviour?
    YesInterface + polymorphismNoSealed records, simple switches
  4. Record the choicein the team's decision log, with an example

4 steps in order. Play them, or step through them one at a time.

4Mixing Both Styles Deliberately

The two styles can live in one hierarchy, and sometimes should. A sealed interface may still declare a few methods that every variant implements, typically core behaviour that is intrinsic to each type, while the many cross-cutting operations such as mapping to an API DTO or to a database row are switches elsewhere. Conversely, an open interface for plugins may hand the framework a small sealed result type, so the framework can switch over the outcomes.

Java
sealed interface OrderState permits Draft, Placed, Shipped, Cancelled {
boolean canCancel(); // intrinsic, implemented by each state
}
record Draft() implements OrderState { public boolean canCancel() { return true; } }
// ... Placed, Shipped, Cancelled likewise
static OrderStatusDto toDto(OrderState s) { // cross-cutting, one switch
return switch (s) {
case Draft d -> new OrderStatusDto("draft", true);
case Placed p -> new OrderStatusDto("placed", true);
case Shipped sh -> new OrderStatusDto("shipped", false);
case Cancelled c -> new OrderStatusDto("cancelled", false);
};
}

The danger is mixing by accident: half the operations as methods and half as switches with no reason, so a new developer cannot tell where to put the next one. Notice the rule in the example: behaviour that defines the state lives in the state, while presentation and integration live in switches near the edge. Writing that rule down is what makes the mix deliberate.

One more caution for switches: a default branch defeats exhaustiveness checking, because the compiler then assumes every unknown case is handled. For sealed hierarchies, teams should leave out default so that adding a variant breaks the build where it should.

5Making the Rule Stick Across Teams

Principles alone do not change long-lived code. I would write the decision rule as a short architecture decision record, one or two pages, with real examples from our own systems: here is our PaymentGateway and why it is an interface, here are our ledger events and why they are sealed records. Code reviewers then have something concrete to point to. A few architecture tests, for example checking that sealed domain hierarchies are not switched over with a default branch, catch the most common slip automatically.

Finally, I would review the rule after a year by looking at change history. If a sealed hierarchy has gained a variant every sprint and each one touches thirty switches, it was probably an open set and should become an interface. If an interface has gained a new method every month and every implementation changes each time, it may be a closed set that wants pattern matching. The rule is a starting point that our own data refines.

6Follow-up questions

Is the visitor pattern still useful?

The visitor pattern was the classic OO way to add operations to a closed hierarchy without editing each class: each type gets one accept method, and each operation is a visitor class with one method per type. Sealed types with pattern switches give the same benefit with much less ceremony and with compiler-checked exhaustiveness, so in modern Java visitors are mostly found in older code and in libraries that must support older Java versions.

Does choosing sealed types hurt encapsulation?

It changes where behaviour lives, but not who owns it. The sealed hierarchy and its operations are owned by one team, often in one package, so the data being public records is a deliberate choice: the variants are the domain's vocabulary. Invariants still belong in the records' compact constructors. What we give up is the ability for outsiders to add variants, which in this style is the point.

7Conclusion

In this answer, we described the expression problem as a grid of types and operations, where OO polymorphism makes adding types cheap and operations expensive, and sealed types with pattern switches do the opposite while the compiler checks exhaustiveness. The decision rule follows who adds variants and what changes more often: interfaces where other teams or plugins add types, sealed hierarchies where one team owns the variants and operations keep growing. Mixing both is fine when the rule is explicit, and the rule sticks when it is written down with our own examples and revisited using change history.

What to say in the interviewAbout 90 seconds aloud

Open with

The expression problem is about extending a family of types in two directions: new types and new operations. With classic object-oriented polymorphism, each class implements all the operations, so adding a type is one new class, but adding an operation means changing the interface and every implementation, possibly across teams.

Then, if they want more

With sealed types and pattern-matching switches, each operation is one function with a switch over all variants, so adding an operation is easy, and adding a variant means editing every switch, although the compiler finds every one for me as long as there is no default branch.

My guidance to teams is based on who adds variants and what changes more often. If other teams or plugins add types, like payment providers or exporters, use interfaces and polymorphism, because the interface is the extension point.

If one team owns a closed set of variants, like the events of an aggregate, order states or the result of an operation, and the operations keep growing, use sealed records and pattern switches.

Mixing is fine if it is deliberate, for example intrinsic behaviour as methods on the sealed types and integration or presentation code as switches at the edge.

I would write this rule down as an architecture decision record with examples from our own systems, and revisit it using change history: a sealed type that gains variants all the time probably wants to be an interface, and vice versa.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
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 "Modern Java supports both object-oriented polymorphism and data-oriented pattern...": https://scrivio-interview-library.netlify.app/java/oop-principles/73eec110ca/