DevOps Zone is brought to you in partnership with:

Java/Javascript software developer, interested in full stack software development based on open source frameworks and tools. Likes to learn new technologies, hang out on stackoverflow and blog on day to day software development tips and tricks. Aleksey is a DZone MVB and is not an employee of DZone and has posted 13 posts at DZone. You can read more from them at their website. View Full User Profile

Java 8 Optional: How to Use it

05.12.2014
| 10452 views |
  • submit to reddit

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 if applicable, 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.

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 be used then?

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

In the context of domain driver development, this means certain service, repository or utility methods such as the one shown above.

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 Optional and 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

Published at DZone with permission of Aleksey Novik, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)