Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite this nested conditional using guard clauses and pattern matching for instanceof:

Java
if (o != null) {
if (o instanceof Order) {
Order ord = (Order) o;
if (ord.total() > 0) {
return ord.total();
}
}
}
return 0;

We can write if (!(o instanceof Order ord)) return 0; return ord.total() > 0 ? ord.total() : 0;. The null check disappears because instanceof is always false for null, and the cast disappears because the pattern declares ord already typed as Order. ord is in scope after the negated early return because of flow scoping: the compiler knows that if we got past the guard, the match succeeded. Guard clauses like this flatten the nesting so the main path reads straight down, and with records and sealed types a switch with patterns can be clearer still.

Why this question is asked

Deeply nested conditionals are one of the most common readability problems in business code, and code that checks for null, checks the type, casts and then checks a value is the classic shape. Interviewers ask for this rewrite because it touches three things at once: the guard clause technique, the precise behaviour of instanceof with null, and the scoping rules of pattern variables, which surprise many people the first time. In this answer, we will recap what the original code does, rewrite it step by step, explain why the pattern variable is still in scope after the guard, and then look at a switch with patterns as an alternative.

1A Quick Recap of the Original Code

The original method takes an Object, checks that it is not null, checks that it is an Order, casts it, and returns its total if the total is positive. In every other case it falls out of the nested ifs and returns 0. For the examples, let us assume Order is a record with an int total.

Java
record Order(int total) { }
static int positiveTotal(Object o) {
if (o != null) {
if (o instanceof Order) {
Order ord = (Order) o;
if (ord.total() > 0) {
return ord.total();
}
}
}
return 0;
}
positiveTotal(new Order(50)); // 50
positiveTotal(new Order(-5)); // 0
positiveTotal("text"); // 0
positiveTotal(null); // 0

Notice that the interesting line, return ord.total(), is three levels deep, and the reader has to keep three conditions in mind to understand when it runs. The type is also written three times: in the instanceof, in the cast and in the declaration.

2Rewriting It With a Guard Clause and a Pattern

A guard clause is an early return at the top of a method that handles the cases we are not interested in, so the rest of the method only deals with the main case. Pattern matching for instanceof, final since Java 16, lets us test the type and declare a typed variable in one step: o instanceof Order ord is true when o is an Order, and in that case ord is o already cast to Order.

Java
static int positiveTotal(Object o) {
if (!(o instanceof Order ord)) return 0; // guard: not an Order, or null
return ord.total() > 0 ? ord.total() : 0; // main path, ord is an Order here
}
positiveTotal(new Order(50)); // 50
positiveTotal(new Order(-5)); // 0
positiveTotal(null); // 0

Notice what disappeared. The null check is gone because instanceof is defined to be false when the value is null, so the guard already returns 0 for null. The cast is gone because the pattern does it. The nesting is gone because the guard handles the uninteresting cases first. The last line could also be written as Math.max(ord.total(), 0), which gives the same result here.

3Why ord Is Still in Scope After the Guard

The surprising part is that ord is used on a line after the if, outside the condition where it was declared. This works because pattern variables use flow scoping: a pattern variable is in scope wherever the compiler can prove that the match succeeded. In if (o instanceof Order ord) { ... }, that is inside the braces. In if (!(o instanceof Order ord)) return 0;, the if body runs when the match failed, and it always returns. So any code after the if can only be reached when the match succeeded, and ord is in scope there.

The guard must really leave the method, or the rule does not apply. If the if body could complete normally, the compiler could no longer prove that the match succeeded, and ord would not be in scope.

Java
if (!(o instanceof Order ord)) return 0;
System.out.println(ord.total()); // fine: only reached when o is an Order
if (!(o instanceof Order ord2)) System.out.println("not an order");
System.out.println(ord2.total()); // error: cannot find symbol ord2
Step throughFlow scoping of ord in the guard clause
  1. Is o an Order (and not null)?
    YesBind ord and continue past the guardNoRun the if body: return 0
  2. Code after the ifcan only be reached when the match succeeded
  3. ord is in scope and typed as Orderord.total() compiles

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

The compiler puts ord in scope wherever the match is certain to have succeeded.

4Why Guard Clauses Help

Guard clauses turn a pyramid of nested conditions into a flat list: first reject what we do not handle, then do the real work. Each guard can be read on its own, and the main path reads straight down the left margin. They also scale: if we later need to reject cancelled orders, we add one more guard line instead of a fourth level of nesting.

Java
static int positiveTotal(Object o) {
if (!(o instanceof Order ord)) return 0;
if (ord.cancelled()) return 0; // a new rule, if Order gains a cancelled flag, is one more guard
return Math.max(ord.total(), 0);
}

5Alternative: A Switch With Patterns

Since Java 21, a switch can match type patterns with guards written with when. When an Object can be one of several types, this states every case side by side, which can be clearer than a chain of instanceof checks. One detail matters: a switch with patterns throws NullPointerException on null unless it has a case null, so we combine it with default.

Java
static int positiveTotal(Object o) {
return switch (o) {
case Order ord when ord.total() > 0 -> ord.total();
case null, default -> 0; // without case null, null would throw
};
}
sealed interface Doc permits Order2, Refund { }
record Order2(int total) implements Doc { }
record Refund(int amount) implements Doc { }
static int signedAmount(Doc d) {
return switch (d) {
case Order2 o -> o.total();
case Refund r -> -r.amount(); // no default: the compiler checks every case
};
}

Notice the second example. With a sealed interface, the switch needs no default, and if someone adds a new kind of Doc, the switch stops compiling until it is handled. That is the point where patterns stop being a shorter if and start being a safety feature.

6Follow-up questions

Is the null check really safe to remove?

Yes. The Java Language Specification defines x instanceof T as false when x is null, and the same holds for patterns. So the guard rejects null exactly as the original outer if did.

Can the pattern variable be reassigned?

Yes, a pattern variable is not implicitly final, unless we declare it final in the pattern. Reassigning it is legal but confusing, so most style guides treat it as effectively final.

When are guard clauses a bad idea?

When a method has many early returns scattered through a long body, the exits become hard to see. Guards work best at the top of a short method; if there are many, the method usually needs splitting.

7Conclusion

In this answer, we rewrote a three-level conditional as one guard clause with pattern matching for instanceof. The null check disappeared because instanceof is false for null, and the cast disappeared because the pattern declares a typed variable. Flow scoping puts ord in scope after the negated early return, because the code there is only reachable when the match succeeded. We also saw that a switch with patterns and a guard is an alternative, with case null to avoid an exception, and that over sealed types it adds a compile-time check of every case.

What to say in the interviewAbout 90 seconds aloud

Open with

I would write: if (!(o instanceof Order ord)) return 0; return ord.total() > 0 ? ord.total() : 0. Three things change. The null check goes away because instanceof is defined to be false for null, so the guard already returns 0 for it.

Then, if they want more

The cast goes away because the pattern Order ord tests the type and binds a variable that is already an Order. And the nesting goes away because the guard clause rejects the cases we do not care about first, so the main path is one line at the left margin.

The interesting rule is why ord is usable after the if. Pattern variables have flow scoping: they are in scope wherever the compiler can prove the match succeeded. The if body runs only when the match failed, and it always returns, so code after it can only be reached when o was an Order.

If the body could fall through, ord would not be in scope. As an alternative, since Java 21 I could use a switch: case Order ord when ord.total() > 0 -> ord.total(); case null, default -> 0. I need case null there, because a pattern switch throws on null.

With sealed types and records, a switch without default also gets exhaustiveness checking, which is even better.

About this answer

Last updated
12 November 2026
Versions it names
Java 16, 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 "Rewrite this nested conditional using guard clauses and pattern matching for instanceof:": https://scrivio-interview-library.netlify.app/java/operators-and-control-flow/f15423a53d/