Muhammed Senussi
Muhammed Senussi
  • Muhammed Senussi
Records, Sealed Types and Pattern Matching Belong TogetherJava

Java picked these three up over several releases and each looked modest on its own. Together they gave the language something it did not have: exhaustiveness.

Modelling a closed set

Declare a sealed interface, implement it with records, and switch over it. The compiler now knows every shape the type can take and refuses to compile a switch that misses one. Add a case a year later and every switch that needs attention becomes a compile error rather than a production surprise.

  • Records give the data carrier without the ceremony.
  • Sealed types close the hierarchy so it can be reasoned about.
  • Pattern matching destructures without a cast.

This is as close as Java has come to algebraic data types, and it models a domain far better than an enum plus a bag of nullable fields.

2 Comments

  • Daan Visser

    March 18, 2024

    Exhaustiveness checking alone justified the upgrade for our domain layer. We found three unhandled cases the day we turned it on.

    • Muhammed Senussi

      Muhammed Senussi

      AuthorMarch 18, 2024

      That is the usual story. The cases were always there; the compiler just had no way to point at them before.

Leave a comment