Skip to main content
adaptive distributed systems intent-based dynamic consistency in java 21

Modeling Intents with Java Records and Sealed Interfaces

3 min read Chapter 3 of 25
Summary

Java Records and sealed interfaces model intents immutably...

Java Records and sealed interfaces model intents immutably and safely.

Modeling Intents with Java Records and Sealed Interfaces

Introduction

Java Records and sealed interfaces are powerful tools for modeling domain data and behaviors in a concise, expressive, and type-safe manner. This section explores how these features can be leveraged to create robust and maintainable intent models, focusing on immutability, serialization safety, and exhaustive pattern matching.

Immutability and Records

Immutability is a fundamental principle in designing robust and predictable software systems. Java Records provide a built-in mechanism for creating shallowly immutable data carrier classes, which is ideal for intent modeling. By using records, developers can ensure that once an intent object is created, its state cannot be modified accidentally or maliciously, thereby reducing the risk of data inconsistencies and improving the overall reliability of the system.

Sealed Interfaces for Intent Hierarchies

Sealed interfaces, introduced in Java 17, allow for the definition of closed hierarchies where the set of permitted subclasses is explicitly declared. This feature is particularly useful for modeling intents, as it enables the compiler to verify that all possible intent types are accounted for, thereby preventing errors due to unhandled cases. By combining sealed interfaces with records, developers can create a robust and expressive intent model that is both immutable and exhaustive.

Exhaustive Pattern Matching

Exhaustive pattern matching is a key benefit of using sealed interfaces. By leveraging this feature, developers can ensure that all possible intent types are handled explicitly, reducing the risk of errors due to unhandled cases. The following example demonstrates how exhaustive pattern matching can be applied to an intent hierarchy:

public sealed interface Intent permits PlaceOrder, CancelOrder, UpdateShipping {
    String correlationId();
}

public record PlaceOrder(String correlationId, String sku, int quantity) implements Intent {}
public record CancelOrder(String correlationId, String reason) implements Intent {}
public record UpdateShipping(String correlationId, String newAddress) implements Intent {}

public void handleIntent(Intent intent) {
    switch (intent) {
        case PlaceOrder p -> System.out.println("Ordering: " + p.sku());
        case CancelOrder c -> System.out.println("Cancelling: " + c.reason());
        case UpdateShipping u -> System.out.println("Moving to: " + u.newAddress());
        // No default required if all 'permits' are covered
    }
}

Serialization Safety

Serialization safety is another critical aspect of intent modeling. Java Records improve serialization safety by using the canonical constructor, which ensures that the record’s state is properly reconstructed during deserialization. This feature is particularly important for intents, as it guarantees that the intent’s state is preserved across different execution contexts.

Comparison with Traditional Classes

The following table summarizes the key differences between traditional classes and Java Records for intent modeling:

FeatureTraditional ClassJava Record
ImmutabilityManual (final fields)Built-in (Default)
BoilerplateHigh (Getter/Setter/toString)Minimal (Header only)
InheritanceFullNone (Implicitly final)
SerializationFragile (Field-based)Robust (Constructor-based)

Conclusion

In conclusion, Java Records and sealed interfaces provide a powerful combination for modeling intents in a robust, maintainable, and type-safe manner. By leveraging these features, developers can ensure immutability, serialization safety, and exhaustive pattern matching, thereby improving the overall reliability and predictability of their software systems.

Sources

[1] OpenJDK. (2021). JEP 409: Sealed Classes. https://openjdk.org/jeps/409 [2] Foojay. (2022). Sealed Interfaces & Pattern Matching: Java’s Modern Capabilities. https://foojay.io/today/sealed-interfaces-and-pattern-matching-a-quick-dive-into-javas-modern-capabilities/ [3] Baeldung. (2022). Sealed Classes and Interfaces in Java. https://www.baeldung.com/java-sealed-classes-interfaces