In Java 8 you can return an Optional
instead of a null
. Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value."
In practice, why is this useful? Also, is there any case where using null
would be preferred? What about performance?
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
By the way, here is how Optional is described in the Java SE 11 documentation: “ 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.
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. A variable whose type is Optional should never itself be null .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With