How To Avoid NullPointerException? 3 - Optional
How To Avoid NullPointerException? 3 - Optional
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-
nullvalue.
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
Optionalshould never itself benull; it should always point to anOptionalinstance.
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:
Optionalis primarily intended for use as a method return type where there is a clear need to represent “no result,” and where usingnullis likely to cause errors
So that means you should not use Optional for
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 forOptional. It clearly told caller that output may not have value, and please handle it properly. - Property may not exist
e.g HttpClient.connectTimeout()
Before havingOptional, 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?
- Caller is notified that the output may have no value.
- null value is discovered earlier,
Optional.ofwill throw NPE when input is null. Hence preventing problem to happen in downstream.Optional.getwill throwNoSuchElementExceptiononce it is called without containing value, where we got NPE util we call method on null reference.
- Reduce the use of null. You will not write
return null;any more if you useOptional. Eliminate the use of null, will of course, reduce the chance you got NPE.
Feel free to put any comment.
Comments
Post a Comment