Data Oriented Programming with Java

Java and Object-Oriented Programming

Java has been with us for more than 30 years now. It was designed from the ground up as a purely object-oriented language. The mantra “everything is an object” (well, almost—primitives aside) has been deeply ingrained in Java’s DNA from day one. This object-oriented foundation helped Java become one of the most popular programming languages in the world, powering everything from enterprise applications to Android mobile apps.

The OO paradigm has served us well, enabling us to build complex, maintainable systems.
But the language has matured and evolved over the last few years. We’ve learned that while object-oriented programming is powerful, it’s not always the best tool for every job.

Object-oriented programming in Java is built on fundamental principles: encapsulation, inheritance, polymorphism, and abstraction.
These principles allow us to model complex systems by bundling data with the methods that operate on that data, creating reusable and maintainable code through class hierarchies.

Object-oriented programming offers significant advantages: code reusability through inheritance, intuitive modeling of real-world entities, and clear separation of concerns through encapsulation.
However, it also comes with drawbacks: deep inheritance hierarchies can become fragile and difficult to maintain, mutability can lead to unexpected side effects, and the tight coupling between data and behavior can make code harder to reason about and test.

Is there a way to avoid dealing with these disadvantages in certain cases?

To answer this question, we need to examine features that have been added to the JDK over the last few years. By combining these new features, we may be able to mitigate some of these traditional OO disadvantages.

Algebraic Data Types (ADT)

Oh… there you go. Algebra!? Seriously?!

Well, it’s simpler than you might think, at least the parts that are relevant for us here.

In computer programming, an algebraic data type is a composite data type — a type formed by combining other types.
An algebraic data type is defined by two key constructions: a sum and a product.
These are sometimes referred to as “Or” and “And” types.

Wikipedia

OK — that already sounds more like our daily business, right?

So let’s take a closer look at what exactly sum types and product types are and how they can be represented in Java.

Sum Types — “OR”

A sum type represents a choice between different possibilities. It can hold a value that matches one of several defined variants. For example, a shape can be either a circle, a rectangle, or a triangle. Of course, there are many more shapes to choose from — if we define them as choices.

An example of a sum type in Java is an Enum:

enum Shape {
    RECTANGLE, CIRCLE, TRIANGLE;
}

Another, more powerful example is Sealed Types.

Sealed Types

Sealed types were introduced to Java with JDK 17. We can have sealed classes and sealed interfaces.

A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so.

JEP 409: Sealed Classes
sealed interface Shape permits Circle, Rectangle, Triangle {}

Here, only the types Circle, Rectangle, and Triangle are allowed to implement the Shape interface. If we had other types like Hexagon or Oval, they would not be permitted to implement the Shape interface.
This means we have a controlled, finite set of types, known at compile time, that can implement Shape. This is valuable information that the compiler can leverage.

Product Types — “And”

A product type combines multiple types. A value of a product type contains a value for each of its component types.
According to this definition, any immutable class that only holds data fields but provides no methods to alter that data can be considered a product type.

Since JDK 16, we even have a specific name for such a product type: Record.

Records

JDK 16 introduced records to Java.
Records are

carriers of immutable data and can be thought of as nominal tuples

JEP 395: Records

which are simply tuples with names.

record Rectangle(int a, int b) {}
record Circle(int radius) {}
record Triangle(int a, int b, int angle) {}

Once a record is instantiated, the data it contains cannot be modified (not even by reflection!). This characteristic makes records perfect for modeling data as data — nothing more, nothing less.
If we want to change the data, we must create a new record instance with the modified data.
JEP 468: Derived Record Creation (also known as “Withers”) will make creating new records with data derived from existing records even easier.

The data in a record could be validated in the record’s constructor, making it impossible to create invalid record instances.

Why Are Algebraic Data Types Interesting for Us?

The answer is: Pattern Matching.

Pattern matching

Pattern matching is a programming mechanism that tests whether a value’s structure and content match a specified pattern, then destructures (binds/extracts) its components for use if the match is successful.
Key behaviors of pattern matching include:

  • Testing: Checking the exact structure match (e.g., is it a Shape?)
  • Binding: Named captures of parts (e.g., Circle c binds c, allowing access to c.radius)
  • Exhaustiveness: Ensuring all cases are covered (compiler-checked for ADTs)
  • Guards: Adding conditions (e.g., Circle c when c.radius > 0)

Since JDK 16, we have Pattern Matching for instanceof.
Instead of writing:

if (o instanceof Shape) {
    Shape s = (Shape) o;
    ...
}

we can now write it in a much shorter, more concise way:

if (o instanceof Shape s) {
    ...
}

When we combine this with Pattern Matching for switch, which became final in JDK 21, we can handle different Shape implementations in a switch statement. Since our Shape type is a sealed interface, the compiler already knows all possible implementing types for the switch statement. The compiler can therefore check whether the switch statement is exhaustive (covers all possible cases). This removes the need for a default clause, which is considered good practice.

double area(Object o) {
    if (o instanceof Shape s) {
        return switch (s) {
            case Rectangle r -> r.a() * r.b();
            case Circle c -> Math.PI * Math.pow(c.radius(), 2);
            case Triangle t -> 0.5 * t.a() * t.b() * Math.sin(t.angle());
        };
    }
    throw new IllegalArgumentException("Object is not a known shape.");
}

If we additionally combine this with JEP 440: Record Patterns, which was also finalized in JDK 21, our switch statement can be written even more concisely:

double area(Object o) {
        if (o instanceof Shape s) {
            return switch (s) {
                case Rectangle(int a, int b) -> a * b;
                case Circle(int radius) -> Math.PI * Math.pow(radius, 2);
                case Triangle(int a, int b, int angle) -> 0.5 * a * b * Math.sin(angle);
            };
        }
        throw new IllegalArgumentException("Object is not a known shape.");
    }

Here the records are deconstructed, and its elements are bound to variables, which can then be used to calculate the switch result.
If we would add a new shape (like Heaxagon) to the allowed shapes, then the compiler would warn us that the switch expression does not cover all possible values.
This is only possible because we do not have a default branch in the switch statement.

Another important observation is the separation of the definition of the data from the operation on the data. The area method is not part of the seald interface, but can reside somewhere else.

Additional enhancements for pattern matching include JEP 456: Unnamed Variables & Patterns in JDK 22 and Primitive Types in Patterns, instanceof, and switch, which is still in preview.

What is Data-Oriented Programming (dop)?

So why is all this talk about algebraic data types, pattern matching, records, sealed classes, and so on?
Perhaps we can combine these features in such a way that their sum adds up to more than its individual parts. In fact, when we combine sealed classes, records, pattern matching for switch, and record patterns, we have all the ingredients for Data-Oriented Programming.
Data-Oriented Programming should follow specific principles that shift our focus from objects to data.

The Four Principles of Data-Oriented Programming

According to Brian Goetz’s seminal work on this topic [1], Data-Oriented Programming follows four key principles:

  1. Model the data, the whole data, and nothing but the data
  2. Data is immutable
  3. Validate at the boundary
  4. Make illegal states unrepresentable

Let’s examine how Java’s modern features support each of these principles.

Principle 1: Model the Data, the Whole Data, and Nothing but the Data

This principle emphasizes separating data modeling from behavior. Instead of bundling data with methods that operate on it (as in traditional OOP), we model data structures as pure data carriers.
This can be achieved through a combination of sealed classes and records. Sealed classes define the set of possible data variants, while records define the structure of each variant. This separation allows us to add new operations on the data without modifying the data definitions themselves.

sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(int radius) implements Shape {}
record Rectangle(int a, int b) implements Shape {}
record Triangle(int a, int b, int angle) implements Shape {}

// When the permitted subclasses are small in size and number, it may be convenient to declare them in the same source file as the sealed class.
// When they are declared in this way, the sealed class may omit the permits clause and the Java compiler will infer the permitted subclasses from the declarations in the source file.
sealed interface Shape {
    record Circle(int radius) implements Shape {}
    record Rectangle(int a, int b) implements Shape {}
    record Triangle(int a, int b, int angle) implements Shape {}
}

Principle 2: Data is Immutable

Records are immutable by design. Once created, their component values cannot be changed. This eliminates entire categories of bugs related to unexpected state mutations and makes code easier to reason about, especially in concurrent contexts.
The immutability of records ensures that data flows through our programs predictably, without hidden side effects.

Principle 3: Validate at the Boundary

Data should be validated when it enters the system (at the boundary), not throughout the codebase. This can be done before records are instantiated or within a record’s compact constructor:

record Circle(int radius) implements Shape {
    public Circle {
        if (radius <= 0) {
            throw new IllegalArgumentException("Radius must be positive");
        }
    }
}

By validating in the constructor, we ensure that invalid Circle instances can never exist in our system.

Principle 4: Make Illegal States Unrepresentable

This principle encourages us to design our data types so that invalid states simply cannot be represented in code.

Through validation in record constructors, we prevent the creation of invalid data.
Additionally, pattern matching with switch on sealed types ensures exhaustiveness—the compiler won’t allow us to miss cases.
When we avoid using a default clause, the compiler will warn us if we add a new variant to a sealed type without handling it in existing switch statements. This way we don’t have to search through the code ourselves.

// Compiler ensures all Shape variants are handled
String stringify (Shape s) {
    return switch (s) {
        case Circle c -> "It's a circle";
        case Rectangle r -> "It's a rectangle";
        case Triangle t -> "it's a triangle";
        // No default needed - compiler knows this is exhaustive
    };
}

When is Data-Oriented Programming Useful?

Data-Oriented Programming shines in several scenarios:

Domain Modeling: When modeling complex domains with well-defined data structures and operations, DOP provides clarity and type safety. Financial systems, medical records, and configuration data are excellent candidates.

Data Transformation Pipelines: Systems that primarily transform data from one form to another benefit greatly from immutable data structures and pattern matching. ETL processes, compilers, and data processing frameworks are natural fits.

APIs and Data Transfer: When designing APIs or working with external data sources, immutable records provide clear contracts and prevent accidental mutations.

Concurrent Systems: The immutability guarantee of DOP makes it easier to write correct concurrent code without complex synchronization.

Algebraic Problem Domains:
Any domain that naturally maps to algebraic data types—expression evaluators, abstract syntax trees, state machines, or game logic—becomes more expressive with DOP. In many cases, DOP can even replace traditional design patterns like Visitor or eliminate the need for complex recursive methods.

Let’s look at two concrete examples that demonstrate these advantages.

Example 1: State Machine for Order Processing

Consider an order processing system where orders transition through various states. With DOP, we can model this state machine clearly and handle state transitions safely:

sealed interface OrderState permits Pending, Confirmed, Shipped, Delivered, Cancelled {}

record Pending(String orderId, LocalDateTime createdAt) implements OrderState {}
record Confirmed(String orderId, LocalDateTime confirmedAt, String paymentId) implements OrderState {}
record Shipped(String orderId, LocalDateTime shippedAt, String trackingNumber) implements OrderState {}
record Delivered(String orderId, LocalDateTime deliveredAt, String signature) implements OrderState {}
record Cancelled(String orderId, LocalDateTime cancelledAt, String reason) implements OrderState {}

class OrderProcessor {
    // Process order based on current state - exhaustive and type-safe
    static String getStatusMessage(OrderState state) {
        return switch (state) {
            case Pending(var id, var created) -> 
                "Order " + id + " is pending (created: " + created + ")";
            case Confirmed(var id, var confirmed, var paymentId) -> 
                "Order " + id + " confirmed with payment " + paymentId;
            case Shipped(var id, var shipped, var tracking) -> 
                "Order " + id + " shipped - tracking: " + tracking;
            case Delivered(var id, var delivered, var signature) -> 
                "Order " + id + " delivered and signed by " + signature;
            case Cancelled(var id, var cancelled, var reason) -> 
                "Order " + id + " cancelled: " + reason;
        };
    }

    // State transitions with validation
    static OrderState confirmOrder(OrderState state, String paymentId) {
        return switch (state) {
            case Pending(var id, var created) -> 
                new Confirmed(id, LocalDateTime.now(), paymentId);
            case Confirmed c -> c; // Already confirmed
            case Shipped _, Delivered _, Cancelled _ -> 
                throw new IllegalStateException("Cannot confirm order in state: " + state);
        };
    }

    // Check if order can be cancelled
    static boolean canCancel(OrderState state) {
        return switch (state) {
            case Pending _, Confirmed _ -> true;
            case Shipped _, Delivered _, Cancelled _ -> false;
        };
    }
}

Compare this to a traditional OOP approach using the State pattern, which would require:

  • An abstract OrderState class with abstract methods for each operation
  • Multiple concrete state classes, each implementing all operations
  • Complex state transition logic scattered across multiple classes
  • Potential for runtime errors if a state doesn’t handle a transition properly
  • Many code points to fix when a new state is added, but no help from the compiler

With DOP, the compiler ensures we handle all states exhaustively, and all the logic for a particular operation is in one place, making it easier to understand and maintain.

Example 2: JSON Parsing Without Visitor Pattern or Recursion

JSON parsing is a classic use case for the Visitor pattern or recursive methods. With DOP and pattern matching, we can achieve the same result more elegantly:

// Model JSON structure as an ADT
sealed interface JsonValue {}

record JsonString(String value) implements JsonValue {}
record JsonNumber(double value) implements JsonValue {}
record JsonBoolean(boolean value) implements JsonValue {}
record JsonNull() implements JsonValue {}
record JsonArray(List<JsonValue> elements) implements JsonValue {}
record JsonObject(Map<String, JsonValue> fields) implements JsonValue {}

class JsonProcessor {
    // Convert JSON to string representation - no recursion needed!
    public String stringify(JsonValue json) {
        return switch (json) {
            case JsonString(var s) -> """ + s + """;
            case JsonNumber(var n) -> String.valueOf(n);
            case JsonBoolean(var b) -> String.valueOf(b);
            case JsonNull() -> "null";
            case JsonArray(var elements) -> "[" + 
                elements.stream()
                        .map(this::stringify)
                        .collect(Collectors.joining(", ")) + "]";
            case JsonObject(var fields) -> "{" + 
                fields.entrySet().stream()
                      .map(e -> """ + e.getKey() + "": " + stringify(e.getValue()))
                      .collect(Collectors.joining(", ")) + "}";
        };
    }


    // Find value at a path (e.g., "user.address.city")
    public JsonValue findAtPath(JsonValue json, String path) {
        String[] parts = path.split("\.");
        JsonValue current = json;

        for (String part : parts) {
            current = switch (current) {
                case JsonObject(var fields) -> 
                    fields.getOrDefault(part, new JsonNull());
                case JsonArray(var elements) -> {
                    try {
                        int index = Integer.parseInt(part);
                        yield index < elements.size() ? elements.get(index) : new JsonNull();
                    } catch (NumberFormatException e) {
                        yield new JsonNull();
                    }
                }
                default -> new JsonNull();
            };
        }
        return current;
    }
}

// Example usage
class JsonExample {
    public static void main(String[] args) {
        JsonValue user = new JsonObject(Map.of(
            "name", new JsonString("Alice"),
            "age", new JsonNumber(30),
            "address", new JsonObject(Map.of(
                "city", new JsonString("Berlin"),
                "zipCode", new JsonString("10115")
            )),
            "hobbies", new JsonArray(List.of(
                new JsonString("reading"),
                new JsonString("cycling")
            ))
        ));

        JsonProcessor processor = new JsonProcessor();
        System.out.println(processor.stringify(user));
        // Output: {"name": "Alice", "age": 30.0, "address": {"city": "Berlin", ...}, ...}

        JsonValue city = processor.findAtPath(user, "address.city");
        System.out.println(city); // JsonString[value=Berlin]
    }
}

Advantages over Traditional Approaches:

Traditional approaches would require either:

  • Visitor Pattern: Creating a JsonVisitor interface with methods for each type, then implementing concrete visitors for each operation. This spreads the logic across multiple classes and makes adding new operations cumbersome.
  • Recursive Methods with instanceof: Writing deeply nested if-else chains with manual type checks and casts, which is error-prone and verbose.

With DOP:

  • All logic for an operation is in one switch expression
  • The compiler ensures exhaustiveness—we can’t forget a case
  • Pattern matching eliminates boilerplate casting and null checks
  • Adding new operations is straightforward—just write a new method with a switch
  • The code clearly expresses the structure and intent

Is Data-Oriented Programming The New Hammer For All Our Problems?

No, data-oriented programming is not a silver bullet, and it’s not meant to replace object-oriented programming entirely.

When to Stick with OOP:
Traditional OOP remains appropriate for systems where behavior and state are tightly coupled, such as UI frameworks, game engines with complex entity behaviors, or systems that model stateful processes. If your domain naturally involves objects that change state over time and have rich behavioral interfaces, OOP is still the right choice.

When to Use DOP:
Data-Oriented programming excels when your primary concern is modeling and transforming data structures. It’s particularly valuable in functional-style pipelines, parsers, compilers, configuration systems, and data-centric business logic, usually in smaller systems

The Hybrid Approach:
In practice, most modern Java applications benefit from a hybrid approach. Use DOP for data modeling and transformation logic, while employing traditional OOP for stateful components, frameworks, and infrastructure code. The key is choosing the right tool for each problem domain.

Java’s evolution with records, sealed classes, and pattern matching gives us the flexibility to choose the most appropriate paradigm for each part of our system. This isn’t about replacing one approach with another—it’s about expanding our toolkit and making more informed design decisions.

Conclusion

Data-Oriented programming represents a significant evolution in how we can write Java code. By combining sealed classes, records, and pattern matching, we gain powerful tools for modeling data clearly and safely. The four principles—modeling pure data, ensuring immutability, validating at boundaries, and making illegal states unrepresentable—guide us toward more robust and maintainable systems.
As Java continues to evolve, features like derived record creation (withers) and enhanced pattern matching will make Data-Oriented programming even more ergonomic. The language is giving us new ways to think about old problems, and it’s worth exploring how these techniques can improve your codebase.

Resources

  1. Data Oriented Programming in Java by Brian Goetz and Daniel Bryant
  2. Data-Oriented Programming in Java by Gavin Bierman
  3. Data-Oriented Programming in Java – Version 1.1 by Nikolai Parlog
  4. Harnessing Java 21 for Data Oriented Programming by Ken Kousen
  5. Data Oriented Programming in Java 21 by Nicolai Parlog

This article is part of the JAVAPRO special magazine issue:

Java in the Age of AI

Explore how AI is transforming the way we build, secure, and operate software with Java.
From AI agents and new architectural patterns to security, data, and team dynamics—this edition brings together real-world insights for building intelligent, production-ready systems.

Discover the edition https://javapro.io/2026/04/27/04-2026-java-in-the-age-of-ai/→

Total
0
Shares
Previous Post

Avoiding Unsustainable Responsibility

Related Posts