On Saturday, 16 November 2013 at 05:04:42 UTC, Jonathan M Davis
wrote:
I really don't understand this. Optional<T> is one of the most
useless ideas
that I've ever seen in Java. Just use null. It's built into the
language. It
works just fine. And wrapping it in a class isn't going to make
it go away.
Just learn to deal with null properly. I've known many
programmers who have no
problems with null whatsoever, and I'd be worried about any
programmer who is
so scared of it that they feel the need to wrap nullable
objects in another
type which has its own concept of null.
The value of an Option<T> type is that it moves checking for null
into the type system. It forces you to check for null before you
perform any potentially NullPointerException-throwing operations,
whereas using naked class references in Java, it's easy to
forget, or miss a null check, or just ignore it and hope
everything is fine. With Option<T>, you have no choice but to
check for null before you perform an operation on the wrapped
class reference.
The only types which aren't nullable in Java are the primitive
types, and if
you use them in generics (like Optional<T> does), then you get
a class that
boxes the primitive type rather than using the primitive type
directly, and
that object is of course nullable. So, you might as well just
use the class
that boxes the primitive type directly and set its reference to
null when you
need it to be null. And Optional<T> doesn't even protect
against null, since
it's perfectly possible to make its contents null. So, as far
as I can see,
Optional<T> is utterly pointless. IMHO, it's outright bad
software design.
I would have to respectfully disagree with that. Proper use of an
Option<T> type can dramatically reduce the chance of calling a
method on a null object, or even eliminate it entirely.