Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Refactor this conditional chain with modern Java:

Java
double area(Object s) {
if (s instanceof Circle) {
Circle c = (Circle) s;
return Math.PI * c.r() * c.r();
} else if (s instanceof Rect) {
Rect r = (Rect) s;
return r.w() * r.h();
}
throw new IllegalArgumentException();
}

We make Shape a sealed interface that permits only Circle and Rect, write each shape as a record, and replace the instanceof chain with a switch expression using record patterns: case Circle(double r) -> Math.PI * r * r and case Rect(double w, double h) -> w * h. Because the interface is sealed, the switch is exhaustive without a default, so adding a new shape becomes a compile error instead of a runtime exception. The alternative is to give each shape its own area() method; we choose pattern matching when operations live outside the types and polymorphism when the behaviour belongs to them.

Why this question is asked

Chains of instanceof checks and casts were the only option in Java for a long time, and a lot of production code still looks like this. Since Java 21, sealed types, records and pattern matching for switch let us write the same logic in a way the compiler can check. Interviewers ask this to see whether we know the modern features and, more importantly, whether we understand what they buy us beyond fewer lines. In this answer, we will look at what is wrong with the original method, introduce a sealed type and records, rewrite the method as a pattern-matching switch, see how exhaustiveness protects us when a new shape arrives, and compare the result with plain polymorphism.

1What Is Wrong With the Original

Here is the original method, with a call that shows its main weakness.

Java
double area(Object s) {
if (s instanceof Circle) { Circle c = (Circle) s; return Math.PI * c.r() * c.r(); }
else if (s instanceof Rect) { Rect r = (Rect) s; return r.w() * r.h(); }
throw new IllegalArgumentException();
}
area(new Circle(1)); // 3.141592653589793
area("hello"); // compiles, then IllegalArgumentException at runtime
area(new Triangle(3, 4)); // compiles, then IllegalArgumentException at runtime

The parameter type is Object, so the compiler accepts anything, including a String. Each branch repeats the type name three times: in the instanceof, in the cast and in the variable. And the worst part is the last line. When someone adds a Triangle class, nothing tells them that area() needs a new branch. The mistake surfaces only when a triangle reaches this method in production, and the exception has no message to explain it.

2A Sealed Interface and Records

A sealed interface is one that lists exactly which classes may implement it, with the permits clause. The compiler then knows the complete set of subtypes. A record is a compact way to declare an immutable class whose state is a fixed list of components; Java generates the constructor, the accessors such as r(), and equals, hashCode and toString.

Java
sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
new Rect(2, 3).w(); // 2.0
new Rect(2, 3); // Rect[w=2.0, h=3.0]

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 types live in the same file, the permits clause can even be left out, and the compiler infers it from the subtypes it finds there.

3A Switch Expression With Record Patterns

Now the method takes a Shape and uses a switch expression. Each case is a record pattern: it checks the type and, in the same step, pulls the components out into variables.

Java
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
};
}
area(new Circle(1)); // 3.141592653589793
area(new Rect(2, 3)); // 6.0
area("hello"); // does not compile: String is not a Shape

Notice what disappeared: the casts, the repeated type names, and the throw at the end. Case Circle(double r) means 'if s is a Circle, bind its r component to a variable r'. The switch is an expression, so it produces a value directly and every path must return one. We could also write var instead of double inside the pattern, as in case Circle(var r). Pattern matching for switch and record patterns are standard features since Java 21, so this compiles on Java 25 with no preview flags.

4Why No Default Is Needed, and Why That Is the Point

Because Shape is sealed, the compiler knows that Circle and Rect are the only possibilities, so a switch that covers both is exhaustive. No default branch is needed. Now watch what happens when a new shape is added.

Java
sealed interface Shape permits Circle, Rect, Triangle {}
record Triangle(double base, double height) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
}; // error: the switch expression does not cover all possible input values
}

The build fails at exactly the place that needs updating, before any code is deployed. Every switch over Shape in the codebase reports the same error, so the compiler gives us the full list of places to change. This is why we should resist adding default -> throw ... to such a switch: a default makes it exhaustive for any future subtype too, and silently brings back the runtime failure we wanted to remove.

One more detail: a pattern switch throws NullPointerException if s is null, unless we add case null explicitly. That is usually what we want, because a null shape is a bug in the caller.

5The Alternative: Replace Conditional With Polymorphism

The classic object-oriented refactoring for a type check chain is to move each branch into the type it tests. Each shape then knows its own area.

Java
sealed interface Shape permits Circle, Rect { double area(); }
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
record Rect(double w, double h) implements Shape {
public double area() { return w * h; }
}
Shape s = new Rect(2, 3);
s.area(); // 6.0

Here the compiler also protects us, in a different way: a new Triangle must implement area() or it does not compile. There is no switch at all, and adding a shape never touches existing code.

6Choosing Between Pattern Matching and Polymorphism

Both versions are correct, so the real question is where the behaviour belongs. The trade-off is known as the expression problem: with polymorphism, adding a new type is easy but adding a new operation means editing every type; with pattern matching, adding a new operation is easy but adding a new type means editing every switch.

Pattern matching or polymorphism?
QuestionPattern matching switchMethod on each type
Adding a new operation (perimeter, toSvg)add one new method with a switchedit every shape type
Adding a new shapecompiler lists every switch to updateimplement the methods, nothing else changes
Behaviour that belongs to the typeawkward, logic far from datanatural fit
Operations owned by another modulenatural fit; types stay plain dataforces that module's concerns into types
Sealed types make both directions compile-time safe; the choice is about where the code belongs.

So I would use polymorphism when area is part of what a shape is, as it is here, and pattern matching when the operation belongs to a different concern, such as rendering shapes as SVG in a UI module or pricing them in a billing module, where putting that logic into the shape records would mix concerns. In a codebase that models data as sealed records, such as events or API messages, pattern matching is often the natural style.

7Follow-up questions

Can a case add extra conditions?

Yes, with a guard written using when, for example case Circle(double r) when r == 0 -> 0.0. Guards are checked in order, and a guarded case does not count towards exhaustiveness on its own, so we still need an unguarded case for Circle. Put more specific cases before more general ones, or the compiler reports that a case is dominated.

Could we use instanceof patterns without the switch?

Yes. Since Java 16, if (s instanceof Circle c) binds c without a cast, and since Java 21 if (s instanceof Circle(double r)) works too. That already removes the casts, but an if chain is never checked for exhaustiveness, so we would keep the throw at the end and lose the compile-time protection.

Do records work with JPA entities?

Not as entities, because JPA needs mutable, non-final classes with a no-argument constructor. Records are a good fit for value objects, DTOs, projections and embeddables in recent Hibernate versions; check your version for embeddable support. Shapes in this example are pure values, so records are ideal.

8Conclusion

In this answer, we replaced an instanceof chain that accepted any Object and failed at runtime for unknown types. We made Shape a sealed interface with Circle and Rect as records, rewrote area() as a switch expression with record patterns, and saw that the switch is exhaustive without a default, so adding Triangle becomes a compile error at every switch. We also saw the polymorphic alternative with an area() method on each record, and chose between them by asking whether the operation belongs to the types or lives outside them.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start by giving the shapes a proper type. I make Shape a sealed interface that permits Circle and Rect, and write both as records, so Circle(double r) and Rect(double w, double h) get their constructors and accessors for free.

Then, if they want more

Then area takes a Shape instead of Object, and the body becomes a switch expression with record patterns: case Circle(double r) arrow Math.PI times r times r, and case Rect(double w, double h) arrow w times h.

The casts and repeated type names disappear, and so does the throw at the end, because the compiler knows from the sealed interface that those are the only two shapes, so the switch is exhaustive without a default.

That is the real gain: if someone adds Triangle to the permits list, every switch over Shape fails to compile with 'does not cover all possible input values', instead of throwing IllegalArgumentException in production. I would avoid adding a default branch for that reason.

The other option is the classic replace conditional with polymorphism: declare double area() on Shape and implement it in each record, so a new shape must implement it. I would choose that when the behaviour really belongs to the type, as area arguably does.

I would choose pattern matching when the operation belongs somewhere else, like rendering or pricing in another module, because then the shapes stay plain data and adding a new operation is just one new method.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 16, 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 official documentation for the version you use. 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 "Refactor this conditional chain with modern Java:": https://scrivio-interview-library.netlify.app/java/clean-code/5204bd9b6c/