How To Avoid NullPointerException? 3 - Optional

HowToAvoidNPE3

Optional is introduced since java 8, what is it and how do we make use of this class to avoid NPE?

What is Optional?

From Optional java doc

A container object which may or may not contain a non-null value.

Simply speaking, Optional is just like a single element Collection, the key point is it can only contain non-null value.

Optional should never be null

Before using Optional, one key point to know is

Optional should never be null

Please NEVER assign null to Optional.
From API Note of Optional:

A variable whose type is Optional should never itself be null; it should always point to an Optional instance.

I really hope that compiler actually enforced this, instead of putting such note. But fortunately IDE like IntelliJ will warn you for such cases.

When to use

Again from API Note of Optional:

Optional is primarily intended for use as a method return type where there is a clear need to represent “no result,” and where using null is likely to cause errors

So that means you should not use Optional for

  1. [Class field](https://stackoverflow.com/questions/23454952/uses-for-optional
    . Method parameter

Use cases

  • Find something from a bunch of elements, where number of elements can be 0.
    e.g. Stream.max()
    It is the most common use case for Optional. It clear told caller that output may not have value, and please handle it properly.
  • Property may not exist
    e.g HttpClient.connectTimeout()
    Before having Optional, we will probably return -1(the most well known default value) to indicate there is no timeout. Optionalis much clearer. and self explanatory for this example.

How does Optional avoid NPE?

  1. Caller is notified that the output may have no value.
  2. null value is discovered earlier,
    • Optional.of will throw NPE when input is null. Hence preventing problem to happen in downstream.
    • Optional.get will throw NoSuchElementException once it is called without containing value, where we got NPE util we call method on null reference.
  3. Reduce the use of null. You will not write return null; any more if you use Optional. Eliminate the use of null, will of course, reduce the chance you got NPE.

Feel free to put any comment.

Comments