DEV Community

Discussion on: Use Optional / Nullable Reference Types Judiciously

Collapse
 
preslavrachev profile image
Preslav Rachev

As soon as we started using Java 8 at work, I became one of the biggest proponents of using Optional where possible. Soon, though, we realized that optionals in Java suffer from the same problem that they were supposed to help fix. As any other type in Java, an Optional wrapping a value can be NULL as well, unless it has been set to an empty Optional at initialization. This has led to many NPEs, because developers implicitly assumed that if a value wrapped in an Optional is NULL-safe, the same applies to the wrapping Optional.

Long story short, we reduced our use of Optional even in cases where a value could potentially be NULL. Instead, we reverted to using the @Nullable and @NonNull annotations, which most Java IDEs and static code analyzers can use to hint the developers if a Nullity check is needed.

P.S. Nullable types in Kotlin really differ from Optionals in Java in that by default variables in Kotlin must always have a value.

Collapse
 
bob profile image
Bob

Yes. Optional will not just magically eradicate all our NPEs. But it is possible to write better code using Optional. As I said in the above post itself,

"The advantage compared to the normal null references is that the Optional types forces you — or the client of your API — to think about the case when the value is not present."

So now the client of the APIs should check whether the Optional has value or not before using it. For a non-optional variable, they can assume it will never be null. For Kotlin the system itself won't allow null reference to a non-optional. But in Java, we have to ensure we don't mistakenly allow a null reference to a non-optional field.