Optional vs. null. What is the purpose of Optional in Java 8? [duplicate]
In practice, why is this useful?
For example let's say you have this stream of integers and you're doing a filtering:
int x = IntStream.of(1, -3, 5)
.filter(x -> x % 2 == 0)
.findFirst(); //hypothetical assuming that there's no Optional in the API
You don't know in advance that the filter operation will remove all the values in the Stream.
Assume that there would be no Optional in the API. In this case, what should findFirst
return?
The only possible way would be to throw an exception such as NoSuchElementException
, which is IMO rather annoying, as I don't think it should stop the execution of your program (or you'd have to catch the exception, not very convenient either) and the filtering criteria could be more complex than that.
With the use of Optional
, it's up to the caller to check whether the Optional
is empty or not (i.e if your computation resulted in a value or not).
With reference type, you could also return null
(but null
could be a possible value in the case you filter only null
values; so we're back to the exception case).
Concerning non-stream usages, in addition to prevent NPE, I think it also helps to design a more explicit API saying that the value may be present or not. For example consider this class:
class Car {
RadioCar radioCar; //may be null or not
public Optional<RadioCar> getRadioCar() {
return Optional.ofNullable(radioCar);
}
}
Here you are clearly saying to the caller that the radio in the car is optional, it might be or not there.
When Java was first designed it was common practice to use a special value, usually called null
to indicate special circumstances like I couldn't find what you were looking for. This practice was adopted by Java.
Since then it has been suggested that this practice should be considered an anti-pattern, especially for objects, because it means that you have to litter your code with null checks to achieve reliability and stability. It is also a pain when you want to put null
into a collection for example.
The modern attitude is to use a special object that may or may not hold a value. This way you can safely create one and just not fill it with anything. Here you are seeing Java 8 encouraging this best-practice by providing an Optional
object.
Optional helps you to handle variables as available or not available and avoid check null references.