Handling Null values with Guava

Handling null values in Java can be quite annoying. Careless use of null can also be a source of a variety of bugs.

“I call it my billion-dollar mistake.” – Sir C. A. R. Hoare, on his invention of the null reference

“Null sucks.” – Doug Lea

There exists a few guidelines, workarounds and solutions for handling the different occurencess of null values and avoid nasty null pointer (exceptions), for example the Null Object Pattern with its defined neutral (null) behaviour. In the case of returning possible null values from a method or for instance a collection, Guava (Google Core Libraries for Java 1.6+) offers the class Optional.

An non-null Optional reference can be used as an replacement for a nullable object reference. It allows to distinguish between an object reference must be present and an object reference might be absent. An Optional is an immutable instance that may contain a non-null reference to another object. If the Optional doesn’t contain a non-null reference, it contains “nothing”. This nothing is called Absent, it’s never called null.

Use cases for this class are:

  • as method return value, indicating that no result is available instead of returning null
  • to distinguish between unknown and known to have no value
  • to wrap nullable elements for storage in collections that does not support null

Use the static factory method Optional.of() to create a non-null Optional. This method fails fast if it’s called with a null parameter.

Optional longValue = Optional.of(3L);
assertEquals(new Long(3L), longValue.get());

To create an Optional with a possible null value use Optional.fromNullable(). Optional.absent() results in an absent (null) value. Use get() to retrieve a present value (get fails fast with an absent value), you may also define default values with or(someValue) (if value is absent) or retrieve null as return value with orNull(). Guava offers a nice fluent API as usual.

assertEquals("foobar", Optional.fromNullable(null).or("foobar"));

Further informations can be found in the documentation. Be aware that Optional is still marked as @Beta. So it might change in future releases.

Short URL for this post: https://blog.oio.de/yremw
This entry was posted in Java and Quality, Java Basics and tagged , . Bookmark the permalink.

1 Response to Handling Null values with Guava

  1. Pingback: Optional in Java 8 | techscouting through the java news

Leave a Reply

Your email address will not be published. Required fields are marked *