Optional require(s) NonNull

Roland Tepp luolong at gmail.com
Wed Oct 31 03:02:30 PDT 2012

In the view of Brian's answer, I see there is no point in defending my
design choice much further, but I really want to address few of the glaring
issues in Alessio's response before shutting up on this matter.

2012/10/30 Alessio Stalla <alessiostalla at gmail.com>

> But Optional is explicit, while "nullable" is not: you can only
> propagate an Optional value through code that expects an Optional, and
> as soon as you step out of that assumption, you need to handle it
> somehow, perhaps by calling get(). Instead, you can propagate a null
> reference almost everywhere, and it might not get caught until someone
> tries to dereference it. In other words, get() only gets called at the
> boundary between code that expects optional values and code that does
> not, while a null reference can be accessed from anywhere.
Still, the NSEE is implicit in case of optional.get(), not explicit as it
would be with deliberate class cast.

> Because casting an object is considered dangerous operation without
> guarding
> > the cast.
> > That is exactly it - it forces me into thinking about weather the cast is
> > safe as opposed exposing a potentially dangerous (as in - it may blow up
> in
> > your face) to user without predudice.
> That is a problem of expectations - get() should be considered a
> dangerous operation that needs guarding, just like a cast. IDEs can
> help in that regard. A lot of operations are unsafe, yet they don't
> usually require a cast for that reason alone. To make a silly example,
> I doubt you would advocate for
> if(y != 0) {
>   z = x / (NonZero) y;
> }
Now, this is clearly a fallacious argument. If you need to come up with
absurd examples to prove your point, you really don't have a point to prove
(or you'll have to come up with a better examples).

For me, having get() method on Optional and throwing an exception in case
the value is not present does not really telegraph the potentially
dangerous nature of unguarded access to the wrapped value inside.
Requiring a cast to access present value does it much better imho. YMMV.

Language being what it is, unfortunately, the syntactical side of type
guard and typecast pair makes a pretty ugly and explicit code, I must agree.

I would love to be able to use instanceof expression to double as guard
expression and type narrowing like in Ceylon (

    if (optional instanceof Some) {
        // option is known to be of type Some at this point


More information about the lambda-dev mailing list