Lesson 3 of 9 · 25m
Pattern Matching and Switches Without the 2008 Ceremony
Use pattern matching for instanceof, switch patterns, record decomposition, and guarded cases while avoiding cleverness that hides business rules.
For years Java object decomposition followed a ritual: instanceof, cast, assign, then hope the next maintainer understood why. Pattern matching removes the ritual and lets the shape of the data drive the code. Used well, it is precise and readable. Used badly, it becomes a competitive obfuscation round inside a service class.
Start with the simple win
The smallest useful pattern is type matching in instanceof:
if (event instanceof OrderShipped shipped) {
notifier.send(shipped.orderId(), shipped.trackingNumber());
}There is no cast and no second variable declaration. The pattern variable shipped is in scope only where the match is true. That narrower scope is a safety feature, not a syntax novelty.
Modern switches can also return values with arrow labels, replacing the older habit of predeclaring a mutable local and assigning it in every branch. Keep those expressions as decisions, not hiding places for network calls and transaction side effects.
Record patterns decompose values
Record patterns let you pull apart shaped data at the point of use:
if (result instanceof Success(Invoice invoice, Instant processedAt)) {
ledger.post(invoice, processedAt);
}Nested patterns are powerful:
switch (message) {
case InvoiceEvent(Created(CreateInvoiceRequest request, Instant at), var metadata) ->
audit.created(request.customerId(), at, metadata.traceId());
case InvoiceEvent(Cancelled(UUID invoiceId, String reason), var metadata) ->
audit.cancelled(invoiceId, reason, metadata.traceId());
}That compactness is valuable for event handlers and protocol decoders. It is less valuable in ordinary business logic where named intermediate steps explain the workflow.
Guards carry the remaining condition
A guarded pattern adds a condition with when:
return switch (payment) {
case Failed f when f.retryable() -> RetryPolicy.fixedDelay(Duration.ofMinutes(2));
case Failed f -> RetryPolicy.none();
case Authorized a -> RetryPolicy.captureSoon(a.authorizationCode());
case Pending p -> RetryPolicy.none();
case Captured c -> RetryPolicy.none();
};Keep guards small and honest. If the guard is the real decision and the pattern is incidental, write a normal method with a descriptive name instead of burying a policy sentence inside when.
Field notes
- Pattern variables are not ordinary mutable locals; their scope is flow-sensitive.
- Prefer exhaustive switches over default branches when a new enum or sealed subtype should force review.
- Deeply nested patterns can be correct and unreadable at the same time; extract a method when names help.
- Switch expressions should usually be pure decisions, not a hiding place for network calls and transaction side effects.
- Null cases belong at the boundary; passing null deeper because a switch tolerated it is migration backwards.
Was this lesson helpful?