I've recently read about this and seen people using this class, but in pretty much all cases, using null
would've worked as well - if not more intuitively. Can someone provide a concrete example where Optional
would achieve something that null
couldn't or in a much cleaner way? The only thing I can think of is to use it with Maps
that don't accept null
keys, but even that could be done with a side "mapping" of null's value. Can anyone provide me with a more convincing argument? Thank you.
Guava team member here.
Probably the single biggest disadvantage of null
is that it's not obvious what it should mean in any given context: it doesn't have an illustrative name. It's not always obvious that null
means "no value for this parameter" -- heck, as a return value, sometimes it means "error", or even "success" (!!), or simply "the correct answer is nothing". Optional
is frequently the concept you actually mean when you make a variable nullable, but not always. When it isn't, we recommend that you write your own class, similar to Optional
but with a different naming scheme, to make clear what you actually mean.
But I would say the biggest advantage of Optional
isn't in readability: the advantage is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional
and address that case. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, I don't think it addresses the issue nearly as well. This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that other.method(a, b)
could return a null
value than you're likely to forget that a
could be null
when you're implementing other.method
. Returning Optional
makes it impossible for callers to forget that case, since they have to unwrap the object themselves.
For these reasons, we recommend that you use Optional
as a return type for your methods, but not necessarily in your method arguments.
(This is totally cribbed, by the way, from the discussion here.)