Optional is no more Optional

Ranjith Raj D
2 min readSep 28, 2020

--

Java 8 introduced the Value-based Class Optional.

import java.util.Optional;

Consider the Optional class as Container, which helps to check the presence of value before using it. It is by default Immutable. Though, it may contain a reference to mutable objects.

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

If, we ask any java developer to name some exception class in java. NPE would be there at top 3.

Using Optional in your code is like initiating new chat conversation with the below question.

“Are you there?”

In java, we do the same for Objects as a null (obj != null) check. Take a scenario where you might have possibility of having null for variable contact, so we classically do the null check.

String contact = null;
if(contact != null) {
System.out.println("Hi" + contact.trim());
}

But the same code can be written using Optional class.

Optional<String> contact = Optional.of("James Gosling");
contact
.map(name -> "Hi " + name.trim())
.ifPresent(System.out::println);

what if your contact is empty?

Optional<String> contact = Optional.empty();
contact
.map(name -> "Hi " + name.trim())
.ifPresent(System.out::print);

There are some learning and practice required to handle NPE using Optional class approach. Optional is a gift from functional influence on java. Learn and fall in love with a Functional style.

Optional and Optionals in Spring

Spring data SimpleJpaRepository supporting Optional. findOne method returns the Optional as result.

<S extends T> Optional<S> findOne(Example<S> example);

Spring framework designers started to adopt Optional to prevent NullPointerException heavily at JPA side.

Key methods of Optional class (Java-8):

  • .orElse
  • .orElseThrow
  • .get()
  • .orElseGet()

Wrap the .get() block using .isPresent() in if check.

Few more points :

  • Never assign null to Optional, Even though it is technically possible.
  • Check the data presence before getting it from the Optional.
  • Use Constructed Default Object Via the Optional.orElse(), when no data present.
  • Exceptions can be thrown using Optional.orElseThrow()
  • Sometimes, you may need to return null, so use orElse(null).

Optional class have got lot of other new methods in recent java releases. Find the right Method that better suites for your requirement.

Note :

org.springframework.data.util.Optionals is a Utility class that provides methods to work with java.util.Optional.

--

--

Ranjith Raj D
Ranjith Raj D

Written by Ranjith Raj D

Software Architect ✦ Full stack developer ✦ Artist ✦ Autodidact ✦ Codeaholic ✦ https://www.linkedin.com/in/ranjithrajd/

Responses (2)