Understand how pattern matching for instanceof reduces branching boilerplate and where it fits clean Java design.
Pattern matching for
instanceof: A Java feature that combines type checking and safe binding in one expression.
Before pattern matching, Java often required this pattern:
1if (obj instanceof Customer) {
2 Customer customer = (Customer) obj;
3 process(customer);
4}
Modern Java reduces that to:
1if (obj instanceof Customer customer) {
2 process(customer);
3}
That looks small, but it matters because repetitive cast boilerplate used to discourage otherwise simple branching.
The biggest gain is not fewer characters. It is that local branching on a small number of known variants becomes more honest and less noisy.
This is useful when:
Pattern matching for instanceof does not make polymorphism obsolete. If logic is widely distributed across the codebase, the right answer may still be a polymorphic method or a dedicated dispatch structure.
Use the feature when:
Do not use it as permission to scatter ad hoc type switching everywhere.
1String describe(Object result) {
2 if (result instanceof Success success) {
3 return "ok:" + success.id();
4 }
5 if (result instanceof Failure failure) {
6 return "error:" + failure.reason();
7 }
8 return "unknown";
9}
This is often fine because the branching is tight, readable, and tied to one local concern.
Use pattern matching for instanceof to remove noisy local casts. If the same branching logic starts spreading or growing, step back and decide whether the code wants a stronger dispatch model instead.