SteelReed

Search

Search posts, questions…

3. Advanced Java

Java 17, 21 and 25 for backend developers: records, sealed types, pattern matching and what is worth upgrading for

Why Java 8-style code running on a new JDK still ships 'forgot the new status' bugs; records as DTOs with Jackson (and why not as JPA entities), sealed interfaces, pattern switches without default, what Java 25 LTS adds, an upgrade plan to Spring Boot 4 and how to review AI-written modern Java.

18 Nov 20268 min readMid

–

1. The problem

A payment service stores results in a class with a String status and five nullable fields. The team adds a REFUNDED status; the if chain has an else that returns "paid". Three weeks later, 37 refunded transactions still show "paid". All tests are green and the compiler said nothing.

2. Key idea

When the set of cases lives only in the author's head (strings, flags, nullable fields), the compiler can't know which branch is missing. Declare the set in the type and a missing branch becomes a compile error.

Modelling Adding a new status means
String status + nullable fields nobody notices; else swallows the new status
enum + switch with default it compiles, the new status falls into default
Sealed + switch without default every unhandled place is a compile error

Kotlin has sealed class and when, TypeScript has discriminated unions with a never check, Rust has match that must be exhaustive.

2.1 Which tool when?

Tool Use when Don't use when
Record DTOs, Kafka messages, @ConfigurationProperties, value objects (Money) JPA @Entity, objects with changing state
Enum all cases share one shape each case carries different fields
Sealed + records multi-shaped results, domain events extension points for outside plugins
Switch without default sealed types your service owns third-party types that may gain subtypes
Virtual threads (21+) I/O-bound work pure CPU work

Records can't be JPA entities: no no-arg constructor, final fields, and Hibernate needs proxies and dirty checking. Records are shallowly immutable: a List field can still be modified inside, so copy with List.copyOf in the constructor.

Upgrade in order: JDK → framework → new features, each step a deploy you can roll back.

3. In Java

Four result types, each with its own data; map to HTTP with a switch without default.

JAVA
sealed interface PaymentResult permits Approved, Declined, RequiresAction, Failed {}
record Approved(String txId, Money charged) implements PaymentResult {}
record Declined(DeclineReason reason, String message) implements PaymentResult {}
record RequiresAction(String redirectUrl) implements PaymentResult {}          // 3-D Secure
record Failed(String provider, boolean retryable) implements PaymentResult {}
 
static int toStatus(PaymentResult r) {
    return switch (r) {
        case Approved a -> 200;
        case Declined(var reason, var msg) when reason == DeclineReason.FRAUD_SUSPECTED -> 403;
        case Declined d -> 402;
        case RequiresAction ra -> 202;
        case Failed f when f.retryable() -> 503;
        case Failed f -> 502;
    };   // no default
}
// Add Refunded to permits: "the switch expression does not cover all possible input values"

Specific cases (when) go before general ones; null still throws NullPointerException unless there's a case null ->. C# has records and switch expressions but only warns on missing branches.

Polymorphic JSON and Java 21–25 features worth using
  • Polymorphic JSON with sealed types needs @JsonTypeInfo(use = Id.NAME, property = "type"). Jackson 2 also needs @JsonSubTypes, or reading throws InvalidTypeIdException; Jackson 3 (Spring Boot 4) reads permits itself. In both, a top-level List<PaymentResult> loses type due to type erasure: wrap it in record Page(List<PaymentResult> items) or use writerFor(new TypeReference<List<PaymentResult>>() {}).
  • Sequenced collections (21): getFirst(), getLast(), reversed() instead of list.get(list.size() - 1).
  • Text blocks (15) for SQL and JSON in tests; helpful NPEs (14) name the null variable.
  • Flexible constructors (25): validate arguments before super(...), without using this.
  • Scoped values (25): replace ThreadLocal for immutable per-request context, a good fit with virtual threads.
  • Compact source files (25): void main() without an enclosing class, for scripts and learning.

4. Working with AI

Hand to AI: converting POJOs to records, if instanceof chains to pattern switches, generating tests per subtype.

Check in AI-written code:

  • Switches on the service's own sealed types have no default.
  • No record is an @Entity.
  • Records holding collections copy them with List.copyOf, Map.copyOf in the constructor.
  • Polymorphic JSON has @JsonTypeInfo; sealed Lists aren't serialised at top level.
  • The JDK upgrade PR is separate from the PR adopting new features.

5. Exercises

Exercise 1: Review a "modernisation" PR

The AI turned an if instanceof chain into a pattern switch, saying "safer, and I added default just in case". Evaluate and fix it.

JAVA
return switch (r) {
    case Approved a -> 200;
    case Declined d -> 402;
    default -> 500;
};
Solution to Exercise 1

default reopens the closed set: RequiresAction and Failed silently become 500, and so will any future subtype. It's exactly the REFUNDED bug from section 1 in new syntax.

Test: create one instance per subtype (or a @MethodSource over PaymentResult.class.getPermittedSubclasses()) and assert the expected status: RequiresAction yields 500 instead of 202.

Fix: drop default and write all four cases. When a subtype is added later, the compiler points at every place to update.

Exercise 2: Read a lost-type JSON incident

After moving results to sealed types, GET /payments returns [{"txId":"t1","charged":...}] and the Kotlin client reports missing type id property 'type'. GET /payments/{id} still includes "type":"Approved". Diagnose and fix.

Solution to Exercise 2

Diagnosis: the controller returns List<PaymentResult>. Due to type erasure, Jackson sees only List<Object> at top level and doesn't apply @JsonTypeInfo to each element. A single object has the static type PaymentResult, so it gets type.

Fix: return record PaymentPage(List<PaymentResult> items): the field has a full generic type, so Jackson sees PaymentResult. Add a test serialising a list and asserting each element has type. Changing the response shape is a breaking change: tell clients or version it.

Summary

  • LTS: 17, 21, 25; Spring Boot 4 needs Java 17+.
  • Records for DTOs and value objects, not JPA entities; shallowly immutable.
  • Sealed + switch without default: a new subtype is a compile error.
  • Polymorphic JSON needs @JsonTypeInfo; a top-level List loses type.
  • Upgrade the JDK first, the framework next, new features last.

Read more: Enums in Java.

Practice interview questions on this topic

All Java Core questions →

Loading comments…
Next on the roadmapThreads in Java: creating threads, the lifecycle and interruption