Core Java

Java 8 Optional: How to Use it

Java 8 comes with a new Optional type, similar to what is available in other languages. This post will go over how this new type is meant to be used, namely what is it’s main use case.

What is the Optional type?

Optional is a new container type that wraps a single value, if the value is available. So it’s meant to convey the meaning that the value might be absent. Take for example this method:
 
 

public Optional<Customer> findCustomerWithSSN(String ssn) {
    ...
}

Returning Optional adds explicitly the possibility that there might not be a customer for that given social security number.

This means that the caller of the method is explicitly forced by the type system to think about and deal with the possibility that there might not be a customer with that SSN.

The caller will have to to something like this:

Optional<Customer> optional = findCustomerWithSSN(ssn);

if (optional.isPresent()) {
    Customer customer = maybeCustomer.get();
    ... use customer ...
}
else {
    ... deal with absence case ...
}

Or otherwise provide a default value:

Long value = findOptionalLong(ssn).orElse(0L);

This use of optional is somewhat similar to the more familiar case of throwing checked exceptions. By throwing a checked exception, we use the compiler to enforce callers of the API to somehow handle an exceptional case.

What is Optional trying to solve?

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing.

If Optional was there since the beginning, most libraries and applications would likely deal better with missing return values, reducing the number of null pointer exceptions and the overall number of bugs in general.

How should Optional be used then?

Optional should be used as the return type of functions that might not return a value.

This is a quote from OpenJDK mailing list:

“The JSR-335 EG felt fairly strongly that Optional should not be on any more than needed to support the optional-return idiom only.

Someone suggested maybe even renaming it to OptionalReturn”

In the context of domain driver development, this means that Optional should be used as the return type of certain service, repository or utility methods such as the one shown above.

What is Optional not trying to solve

Optional is not meant to be a mechanism to avoid all types of null pointers. The mandatory input parameters of methods and constructors still have to be tested for example.

Like when using null, Optional does not help with conveying the meaning of an absent value. In a similar way that null can mean many different things (value not found, etc.), so can an absent Optional value.

The caller of the method will still have to check the javadoc of the method for understanding the meaning of the absent Optional, in order to deal with it properly.

Also in a similar way that a checked exception can be caught in an empty block, nothing prevents the caller of calling get() and moving on.

What is wrong with just returning null?

The problem is that the caller of the function might not have read the javadoc for the method, and forget about handling the null case.

This happens frequently and is one of the main causes of null pointer exceptions, although not the only one.

How should Optional NOT be used?

Optional is not meant to be used in these contexts, as it won’t buy us anything:

  • in the domain model layer (not serializable)
  • in DTOs (same reason)
  • in input parameters of methods
  • in constructor parameters

How does Optional help with functional programming?

In chained function calls, Optional provides method ifPresent(), that allows to chain functions that might not return values:

findCustomerWithSSN(ssn).ifPresent(() -> System.out.println("customer exists!"));

Useful Links

This blog post from Oracle goes further into Optionaland it’s uses, comparing it with similar functionality in other languages – Tired of Null Pointer Exceptions?

This cheat sheet provides a thorough overview of Optional – Optional in Java 8 Cheat Sheet.

Reference: Java 8 Optional: How to Use it from our JCG partner Aleksey Novik at the The JHades Blog blog.

Aleksey Novik

Software developer, Likes to learn new technologies, hang out on stackoverflow and blog on tips and tricks on Java/Javascript polyglot enterprise development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button