eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll learn about a different paradigm of software development, Data-Oriented Programming. We’ll start by comparing it to the more traditional Object Oriented Programming, and highlight their differences.

After that, we’ll engage in a hands-on exercise applying data-oriented programming to implement the game of Yahtzee. Throughout the exercise, we’ll focus on the DOP. principles, and leverage modern Java features like records, sealed interfaces, and pattern matching.

2. Principles

Data-Oriented Programming is a paradigm where we design our application around data structure and flow rather than objects or functions.  This approach to software design is centered around three key principles:

  • The data is separated from the logic operating on it,
  • The data is stored within generic and transparent data structures,
  • The data is immutable, and consistently in a valid state;

By only allowing the creation of valid instances and preventing changes, we ensure that our application consistently has valid data. So, following these rules will result in making illegal states unrepresentable.

3. Data-Oriented vs. Object-Oriented Programming

If we follow these principles we’ll end up with a very different design than the more traditional Object-Oriented Programming (OOP). A key difference is that OOP uses interfaces to achieve dependency inversion and polymorphism, valuable tools for decoupling our logic from dependencies across boundaries.

In contrast, when we use DOP we are not allowed to mix data and logic. As a result, we cannot polymorphically invoke behavior on data classes. Moreover, OOP uses encapsulation to hide the data, whereas DOP favors generic and transparent data structures like maps, tuples, and records.

To summarize, Data-Oriented Programming is suitable for small applications where data ownership is clear and protection against external dependencies is less critical. On the other hand, OOP remains a solid choice for defining clear module boundaries or allowing clients to extend software functionality through plugins.

4. The Data Model

In the code examples for this article, we’ll implement the rules of the game Yahtzee. First, let’s review the main rules of the game:

  • In each round, players start their turn by rolling five six-sided dice,
  • The player may choose to reroll some or all of the dice, up to three times,
  • The player then chooses a scoring strategy, such as “ones”, “twos”, “pairs”, “two pairs”, “three of a kind”… etc.
  • Finally, the player gets a score based on the scoring strategy and the dice;

Now that we have the game rules, we can apply the Data-Oriented principles to model our domain.

4.1. Separating Data From Logic

The first principle we discussed is to separate data and behavior, and we’ll apply it to create the various scoring strategies.

We can think of a Strategy as an interface with multiple implementations. At this point, we don’t need to support all the possible strategies; we can focus on a few and seal the interface to indicate the ones we allow:

sealed interface Strategy permits Ones, Twos, OnePair, TwoPairs, ThreeOfaKind {
}

As we can observe, the Strategy interface doesn’t define any method. Coming from an OOP background this may look peculiar, but it’s essential to keep data separated from the behavior operating on it. Consequently, the specific strategies won’t expose any behavior either:

class Strategies {
    record Ones() implements Strategy {
    }

    record Twos() implements Strategy {
    }

    record OnePair() implements Strategy {
    }

    // other strategies...
}

4.2. Data Immutability and Validation

As we already know, Data-Oriented Programming promotes the usage of immutable data stored in generic data structures. Java records are a great fit for this approach as they create transparent carriers for immutable data. Let’s use a record to represent the dice Roll:

record Roll(List<Integer> dice, int rollCount) { 
}

Even though records are immutable by nature, their components must also be immutable. For instance, creating a Roll from a mutable list lets us modify the value of the dice later. To prevent this, we can use a defensive copy of the List:

record Roll(List<Integer> dice, int rollCount) {
    public Roll {
        dice = List.copyOf(dice);
    }
}

Furthermore, we can use this constructor to validate the data:

record Roll(List<Integer> dice, int rollCount) {
    public Roll {
        if (dice.size() != 5) {
            throw new IllegalArgumentException("A Roll needs to have exactly 5 dice.");
        }
        if (dice.stream().anyMatch(die -> die < 1 || die > 6)) {
            throw new IllegalArgumentException("Dice values should be between 1 and 6.");
        }

        dice = List.copyOf(dice);
    }
}

4.3. Data Composition

This approach helps capture the domain model using data classes. Utilizing generic data structures without specific behavior or encapsulation enables us to create larger data models from smaller ones.

For example, we can represent a Turn as the union between a Roll and a Strategy:

record Turn(Roll roll, Strategy strategy) {
}

As we can see, we’ve captured a significant portion of our business rules through data modeling alone. Although we haven’t implemented any behavior yet, examining the data reveals that a player completes their Turn by executing a dice Roll and selecting a Strategy. Moreover, we can also observe that the supported Strategies are: Ones, Twos, OnePair, and ThreeOfaKind.

5. Implementing the Behaviour

Now that we have the data model, our next step is implementing the logic that operates on it. To maintain a clear separation between data and logic, we’ll utilize static functions and ensure the class remains stateless.

Let’s start by creating a roll() function that returns a Roll with five dice:

class Yahtzee {
    // private default constructor

    static Roll roll() {
        List<Integer> dice = IntStream.rangeClosed(1, 5)
          .mapToObj(__ -> randomDieValue())
          .toList();
        return new Roll(dice, 1);
    }

    static int randomDieValue() { /* ... */ }
}

Then, we need to allow the player to reroll specific dice values.

static Roll rerollValues(Roll roll, Integer... values) {
    List<Integer> valuesToReroll = new ArrayList<>(List.of(values));
    // arguments validation

    List<Integer> newDice = roll.dice()
      .stream()
      .map(it -> {
          if (!valuesToReroll.contains(it)) {
              return it;
          }
          valuesToReroll.remove(it);
          return randomDieValue();
      }).toList();

    return new Roll(newDice, roll.rollCount() + 1);
}

As we can see, we replace the rerolled dice values and increase the rollCount, returning a new instance of the Roll record.

Next, we enable the player to choose a scoring strategy by accepting a String, from which we’ll create the adequate implementation using a static factory method. Since the player finishes their turn, we return a Turn instance containing their Roll and the chosen Strategy:

static Turn chooseStrategy(Roll roll, String strategyStr) {
    Strategy strategy = Strategies.fromString(strategyStr);
    return new Turn(roll, strategy); 
}

Finally, we’ll write a function to calculate a player’s score for a given Turn based on the chosen Strategy. Let’s use a switch expression and Java’s pattern-matching feature.

static int score(Turn turn) {
    var dice = turn.roll().dice();
    return switch (turn.strategy()) {
        case Ones __ -> specificValue(dice, 1);
        case Twos __ -> specificValue(dice, 2);
        case OnePair __ -> pairs(dice, 1);
        case TwoPairs __ -> pairs(dice, 2);
        case ThreeOfaKind __ -> moreOfSameKind(dice, 3);
    };
}

static int specificValue(List<Integer> dice, int value) { /* ... */ }

static int pairs(List<Integer> dice, int nrOfPairs) { /* ... */ }

static int moreOfSameKind(List<Integer> dice, int nrOfDicesOfSameKind) { /* ... */ }

The use of pattern matching without a default branch ensures exhaustiveness, guaranteeing that all possible cases are explicitly handled. In other words, if we decide to support a new Strategy, the code will not compile until we update this switch expression to include a scoring rule for the new implementation.

As we can observe, our functions are stateless and side-effect-free, only performing transformations to immutable data structures. Each step in this pipeline returns a data type required by the subsequent logical steps, thereby defining the correct sequence and order of transformations:

@Test
void whenThePlayerRerollsAndChoosesTwoPairs_thenCalculateCorrectScore() {
    enqueueFakeDiceValues(1, 1, 2, 2, 3, 5, 5);

    Roll roll = roll(); // => { dice: [1,1,2,2,3] }
    roll = rerollValues(roll, 1, 1); // => { dice: [5,5,2,2,3] }
    Turn turn = chooseStrategy(roll, "TWO_PAIRS");
    int score = score(turn);

    assertEquals(14, score);
}

6. Conclusion

In this article, we covered the key principles of Data-Oriented Programming and how it differs from OOP. After that, we discovered how the new features in the Java language provide a strong foundation for developing data-oriented software.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)