Optional require(s) NonNull

Alessio Stalla alessiostalla at gmail.com
Tue Oct 30 08:26:06 PDT 2012

On Tue, Oct 30, 2012 at 4:02 PM, Roland Tepp <luolong at gmail.com> wrote:
> 2012/10/30 Brian Goetz <brian.goetz at oracle.com>
>> Then what's the problem?  We have these methods already.
>> You suggested moving get to Some/None, and Alessio told you exactly why
>> that was a silly idea.
> I actually suggested removing get() from Absent (NONE) and only moving it
> to instances of Present and only Present.
> Pattern matching is not really an issue here, as most of the use cases
> where you would use Optional, would need to deal with absent values by any
> of the following ways:
> 1. Use some sensible default value if optional is not present (this is
> where I'd use optional.orElse(...) )
> 2. Throw an exception if optional value is otherwise expected to be present
> (i.e. optional.orElseThrow(...))
> 3. Branch off logic based on the fact if the optional value is present
> (checking optional.isPresent())
> The danger of having a get() method directly on Optional is that this
> encourages the direct use of optional.get() which is susceptible to
> NoSuchElementException with the same casualty as NullPointerException's are
> common without use of Optional.

There is a big difference: with get(), the exception occurs at the
exact location where you call get(), i.e. as soon as you need to pass
your Optional value to some method that expects non-optional values.
The problem with NPEs is not that they are thrown, but that they can
be thrown far away from the code that actually caused them.

> Moving it out of the Optional and into the Some/Present will require
> explicit casting of the Optional to Present which at least is more
> deliberate action and force the developer to consider this at least for a
> moment.
> i.e. something like this:
>     Optional<String> optional = ...
>     if (optional.isPresent()) {
>         ((Present) optional).get().split(...);
>     }

If you already bothered to guard it with if (optional.isPresent()) why
the need for casting? And, if you don't guard it, it will fail with a
CCE just as if it would have failed with a NoSuchElementException.


Some gratuitous spam:

http://ripple-project.org Ripple, social credit system
http://villages.cc Villages.cc, Ripple-powered community economy
http://common-lisp.net/project/armedbear ABCL, Common Lisp on the JVM
http://code.google.com/p/tapulli my current open source projects
http://www.manydesigns.com/ ManyDesigns Portofino, open source
model-driven Java web application framework

More information about the lambda-dev mailing list