Optional and Objects: Null Pointer Saviours!

No one loves Null Pointer Exceptions ! Is there a way we can get rid of them ? Maybe . . . 

Couple of techniques have been discussed in this post

  • Optional type (new in Java 8)
  • Objects class (old Java 7 stuff😉 )

Optional type in Java 8

What is it?

  • A new type (class) introduced in Java 8
  • Meant to act as a ‘wrapper‘ for an object of a specific type or for scenarios where there is no object (null)

In plain words, its a better substitute for handling nulls (warning: it might not be very obvious at first !)

Basic Usage

It’a a type (a class) – so, how do I create an instance of it?

Just use three static methods in the Optional class

Plain and simple – create an Optional wrapper containing the value. Beware – will throw NPE in case the value itself is null !

Slightly better in my personal opinion. There is no risk of an NPE here – in case of a null input, an empty Optional would be returned

In case you want to purposefully return an ’empty’ value. ’empty’ does not imply null

Alright – what about consuming/using an Optional?

A simple way is to check whether or not the Optional wrapper has an actual value (use the isPresent method) – this will make you wonder if its any better than using if(myObj!=null)😉  Don’t worry, I’ll explain that as well

One can use the orElse which can be used to return a default value in case the wrapped value is null – the advantage is obvious. We get to avoid the the obvious verbosity of invoking ifPresent before extracting the actual value

I was a little confused with this. Why two separate methods for similar goals ? orElse and orElseGet could well have been overloaded (same name, different parameter)

Anyway, the only obvious difference here is the parameter itself – you have the option of providing a Lambda Expression representing instance of a Supplier<T> (a Functional Interface)

How is using Optional better than regular null checks????

  • By and large, the major benefit of using Optional is to be able to express your intent clearly – simply returning a null from a method leaves the consumer in a sea of doubt (when the actual NPE occurs) as to whether or not it was intentional and requires further introspection into the javadocs (if any). With Optional, its crystal clear !
  • There are ways in which you can completely avoid NPE with Optional – as mentioned in above examples, the use of Optional.ofNullable (during Optional creation) and orElse and orElseGet (during Optional consumption) shield us from NPEs altogether

Another savior! (in case you can’t use Java 8)

Look at this code snippet

What can possibly be null?

  • The Map object
  • The key against which the search is being executed
  • The instance on which the method is being called

When a NPE is thrown in this case, we can never be sure as to What is null?

Enter The Objects class

The requireNonNull method

  • Simply returns the value in case its not null
  • Throws a NPE will the specified message in case the value in null

Why is this better than if(myObj!=null)

The stack trace which you would see will clearly have the Objects.requireNonNull method call. This, along with your custom error message will help you catch bugs faster . . much faster IMO !

You can write your user defined checks as well e.g. implementing a simple check which enforces non-emptiness

Don’t let NPEs be a pain in the wrong place. We have more than a decent set of tools at our disposal to better handle NPEs or eradicate them altogether !


About Abhishek

Currently working as a Senior Product Manager in the Oracle Cloud Application Development team with a focus on Oracle Cloud PaaS portfolio. When not hovering in the clouds, I stay grounded with Java EE
This entry was posted in Java, Java SE and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s