Course – launch – BF – 2023 Discount 30%
We're now running the only sale of the year - our Black Friday launch. All Courses are 30% off until end-of-day today:


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:

public void givenRecordCreationWithOptional_thenCreateItProperly() {
    var emptyDescriptionProduct = new Product("television", 1699.99, Optional.empty());
    Assertions.assertEquals(1699.99, emptyDescriptionProduct.price());

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

As always, you can find the source code over on GitHub.

Course – launch – BF – 2023 Discount 30%
We're now running the only sale of the year - our Black Friday launch. All Courses are 30% off until end-of-day today:


res – REST with Spring (eBook) (everywhere)
Notify of
Inline Feedbacks
View all comments