I had recently discovered the JDK 8’s addition of the
Optional type. The Optional type is a way to avoid
NullPointerException, as API consumers that get
Optional return values from methods are “forced” to perform “presence” checks in order to consume their actual return value. More details can be seen in the
Javadoc.
A very interesting further read can be seen here in this blog post, which compares the general notion of
null and how
null is handled in Java, SML, and Ceylon:
http://blog.informatech.cr/2013/04/10/java-optional-objects
“blank” and “initial” states were already known to
Turing . One could also argue that the “neutral” or “zero” state was required in the
Babbage Engine, which dates back to Ada of Lovelace in the 1800′s.
On the other hand, mathematicians also prefer to distinguish “nothing” from “the empty set”, which is
“a set with nothing inside”. This compares well with “NONE” and “SOME”, as illustrated by the aforementioned
Informatech blog post, and as implemented by Scala, for instance.
Anyway, I’ve given Java’s
Optional some thought. I’m really not sure if I’m going to like it, even if Java 9 would eventually add some syntactic sugar to the JLS, which would resemble that of
Ceylon to leverage
Optional on a language level. Since Java is so incredibly backwards-compatible, none of the existing APIs will be retrofitted to return
Optional, e.g, the following isn’t going to surface the JDK 8:
public interface List<E> {
Optional<E> get(int index);
[...]
}
Not only can we assign
null to an
Optional variable, but the absence of “Optional” doesn’t guarantee the semantics of “SOME”, as lists will still return “naked”
null values. When we mix the two ways of thinking, we will wind up with two checks, instead of one
Optional<T> optional = // [...]
T nonOptional = list.get(index);
// If we're paranoid, we'll double-check!
if (optional != null && optional.isPresent()) {
// do stuff
}
// Here we probably can't trust the value
if (nonOptional != null) {
// do stuff
}
Hence…
-1 from me to Java’s solution
Further reading
Of course, this has been discussed millions of times before. So here are a couple of links: