Video in progress

Records, sealed types and pattern matching in Java 21 give you a "data-oriented programming" style. How do you balance it with classic OOP in one codebase?

The data-oriented style for types that carry data and results (DTOs, events, commands, errors, protocol messages); classic encapsulation for domain objects with rich behavior that protect their own state and invariants. The boundary is between "what this object knows" and "what this object does".

📖 Answer

The principles of data-oriented programming (briefly, following Brian Goetz's definition): model data as transparent, immutable data; make illegal states unrepresentable; write operations separately from the data, using pattern matching.

sealed interface CheckResult permits Approved, Rejected, NeedsReview {}
record Approved(String ref) implements CheckResult {}
record Rejected(String reason, int code) implements CheckResult {}
record NeedsReview(List<String> flags) implements CheckResult {}

String toMessage(CheckResult r) {
    return switch (r) {
        case Approved a                    -> "Tasdiqlandi: " + a.ref();
        case Rejected(var reason, var code) -> "Rad etildi (" + code + "): " + reason;
        case NeedsReview(var flags)        -> "Tekshiruvga: " + String.join(", ", flags);
    };
}

There's no "behavior" inside Rejected here, and there doesn't need to be: it carries a fact.

Where data-oriented works well:

  • messages between services, events, API DTOs;
  • result and error types (Result, validation errors);
  • parsers and ASTs, workflow states.

Where classic OOP stays:

  • aggregates with invariants (Account.withdraw): exposing the state is dangerous;
  • extension points where the set of types is open (plugins, providers);
  • objects that manage resources (connection pools, caches).

The risk in a mixed codebase: two styles for the same concept. For example, order.cancel() in one place and cancellation logic in a switch (order) in another. The team needs a rule: aggregates keep their own behavior; the messages and results around them are records and sealed types. In code review, the question "which object's method should this switch have become?" helps.