Null Check vs Optional? Are they same?

Vaibhav Singh
Javarevisited
Published in
2 min readNov 4, 2020

When this question was asked in an interview, like everyone I answered “Java 8 has introduced this new class Optional in java.util package. By using Optional, we are avoiding null checks and can specify alternate values to return, thus making our code more readable.

But then the interviewer wrote the below code (See Example 1) and asked “Why optional is better, if it is doing pretty much the same thing with null check , thus not achieving any special purpose.”

Example 1 :

String value = null;
Optional<String> optionalValue = someFunction();

if(optionalValue.isPresent())
value = optionalValue.get().toUpperCase();
else
value = "NO VALUE";

VS

String value = null; 
String possibleNull = someFunction();
if(possibleNull != null)

value = possibleNull.toUpperCase();
else
value = "NO VALUE";

Example 2:

private boolean validAddress(NullPerson person) 
{
if (person != null)
{
if (person.getAddress() != null)
{
final Instant validFrom = person.getAddress().getValidFrom();
return validFrom != null && validFrom.isBefore(now());
}
else
return false;
}
else
return false;
}

VS

private boolean validAddress(NullPerson person) 
{
return personOptional.isPresent() && person.getAddress().isPresent() && person.getAddress().getValidFrom().isPresent() && person.getAddress().getValidFrom().isBefore(now());
}

Real Advantage of Optional

It's a library class that has a fairly rich API for dealing with the empty case in a safer way.

Thus Optional way of Example 1 should be :

String value = someFunction().map(String::toUpperCase)
.orElse("NO VALUE");

And Example 2 should have been written as

private boolean validAddress(NullPerson person) 
{
return person.flatMap(Person::getAddress).flatMap(Address::getValidFrom).filter(x -> x.before(now())).isPresent();
}

Disadvantages

Of course, there is no silver bullet…

1 ) On Performance: Wrapping primitive values into an optional instance shows noticeable degrading performance in tight loops. In Java 10 value types might further reduce or remove the penalty.

2) On Serialization: Optional is not serializable but a workaround is not overly complicated.

Conclusion

The main point of Optional is to indicate the absence of a value (i.e null value ) while returning value for the function. It was meant to clarify the intent to the caller.

I believe the problem arises when Optional is used in the same way as earlier NPE checks. Optional Class was meant as a container that contains a value or no value. Thus I am under the opinion that Java should not have provided get() and ifPresent() methods or should have provided alternative mechanisms to facilitate the rerieval( and check behavior.

References :

  1. https://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html
  2. https://nipafx.dev/intention-revealing-code-java-8-optional#
  3. https://dev.to/piczmar_0/java-optional-in-class-fields-why-not-40df
  4. https://ionutbalosin.com/2018/05/optional-api-vs-explicit-null-check-race/
  5. https://www.oracle.com/technical-resources/articles/java/java8-optional.html
  6. https://javarevisited.blogspot.com/2017/04/10-examples-of-optional-in-java-8.html

Questions ? Comments ? Suggestions ?

What’s next?

Follow me on Medium to be the first to read my stories.

--

--

Vaibhav Singh
Javarevisited

I am a #TechnologyEnthusiast #Coder #JavaProgrammer #Blogger (https://linqz.io) #Dreamer. In my free time I love to #Cook, #ShareStories & #VolunteerForPoor.