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. Introduction

In this tutorial, we’ll discuss the possibility of using Optional as a record parameter and why it’s a bad practice.

2. Intended Uses for Optional

Before discussing the relationship between Optional and records, let’s quickly recap the intended uses for Optional in Java.

Typically, before Java 8, we used null to represent the empty state of an object. However, a null as a return value requires null-check validation from the caller code in runtime. If the caller doesn’t validate, it might get a NullPointerException. And getting the exception is sometimes used to identify the absence of value.

The main goal of Optional is to represent a method return value that represents the absence of a value. Instead of having our application crash with NullPointerExceptions to identify the absence of value, we can use an Optional as the return value. Hence, we know at compilation time that the return value holds something or nothing.

Additionally, as it says in the Java docs:

Optional is intended to provide a limited mechanism for library method return types where there is a clear need to represent “no result”, and where using null for that is overwhelmingly likely to cause errors

Therefore, it’s also essential to note what Optional isn’t intended to do. In that matter, we can highlight that Optional isn’t intended to be used as an instance field of any class.

3. Use-Cases for Java Records

Let’s also look at a few concepts about records to get a better foundation about using Optional as a record parameter.

A record is simply a data holder. It fits well when we want to transfer data from one place to another, like from a database to our application.

Let’s paraphrase JEP-395:

Records are classes that act as transparent carriers for immutable data.

A critical definition of records is that they’re immutable. Hence, once we instantiate one record, all its data remains unmodifiable throughout the rest of the program. That’s great for objects that transfer data, as immutable objects are less error-prone.

Records also define accessor methods with the same field name automatically. So, by defining them, we get getters with the same of the defined field.

The JDK record definition also suggests that the data held by a record should be transparent. As a result, if we call an accessor method, we should get valid data. In that case, valid data means the value that truly represents the object state. Let’s paraphrase Project Amber in that matter:

The API for a data class (Record) models the state, the whole state, and nothing but the state.

Immutability and transparency are essential definitions to defend the argument that records must not have an Optional parameter.

4. Optional as a Record Parameter

Now that we have a better understanding of both concepts, we’ll see why we must avoid using Optional as a record parameter.

First, let’s define a record example:

public record Product(String name, double price, String description) {
}

We’ve defined a data holder for a product with a name, price, and description. We can imagine data holders resulting from a database query or HTTP call.

Now, let’s suppose that the product description sometimes isn’t set. In that case, description is nullable. One way of addressing that is by wrapping the description field into an Optional object:

public record Product(String name, double price, Optional<String> description) {
}

Although the code above compiles correctly, we break the data transparency of the Product record.

Additionally, record immutability makes it harder to handle an Optional instance than a null variable. Let’s see that in practice with a simple test:

@Test
public void givenRecordCreationWithOptional_thenCreateItProperly() {
    var emptyDescriptionProduct = new Product("television", 1699.99, Optional.empty());
    Assertions.assertEquals("television", emptyDescriptionProduct.name());
    Assertions.assertEquals(1699.99, emptyDescriptionProduct.price());
    Assertions.assertNull(emptyDescriptionProduct.description().orElse(null));
}

We’ve created a Product with some values and used the generated getters to assert that the record instantiated correctly.

In our product, we defined the variables nameprice, and description. However, since description is an Optional, we don’t get a value immediately after retrieving it. We need to do some logic to open it up to get the value. In other words, we don’t get the correct object state after calling the accessor method. Thus, it breaks the definition of data transparency of a Java record.

We may think, in that case, what do we do with nulls? Well, we can simply let them exist. A null represents the empty state of an object, which in that case is more meaningful than an instance of an empty Optional. In those scenarios, we can notify the users of the Product class that description is nullable by using the @Nullable annotation or other good practices for handling nulls.

Since record fields are immutable, the description field can’t be changed. Hence, to retrieve the description value, we have some options. One is opening it up or returning a default, using orElse() and orElseGet(). Another way is mindlessly using get(), which throws NoSuchElementException if there’s no value. The third is to throw an error if there’s nothing inside of it, using orElseThrow().

In any possible way of handling it, Optional has no meaning, as in any case, we are either returning null or throwing an error. It’s simpler just to let description be a nullable String.

5. Optional as a Return Type

In this section, we’ll explore how to use Optional as a return type effectively. Let’s consider a scenario where we have a User record representing user information:

public record User(String username, String email, String phoneNumber) {
    public Optional<String> getOptionalPhoneNumber() {
        return Optional.ofNullable(phoneNumber);
    }
}

In this example, we have a User record with fields for the username, email, and phoneNumber. The getOptionalPhoneNumber() method returns an Optional<String>, indicating that a phone number might or might not be present:

@Test
public void givenRecordCreationWithNullOptional_thenReturnOptional() {
    User user = new User("john_doe", "[email protected]", null);
    Optional<String> optionalPhoneNumber = user.getOptionalPhoneNumber();

    Assertions.assertEquals(Optional.empty(), optionalPhoneNumber);
}

By returning an Optional, we can decide how to respond – whether to prompt the user to enter a phone number, display a default message, or proceed without it:

optionalPhoneNumber.ifPresentOrElse(
    phone -> // handle if phone present
    () -> // handle if phone is absent
);

Using Optional as a return type in this way helps make the code safer by explicitly addressing the absence of a value. It provides a way to avoid NullPointerException and encourages better handling of potentially missing information.

6. Conclusion

In this article, we saw the definitions of a Java record and understood the importance of transparency and immutability.

We also looked at the intended usage of the Optional class. More importantly, we discussed that Optionals are not suitable to be used as record parameters. Instead, Optional can be more effectively used as a return type in methods.

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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments