I call it my billion-dollar mistake. It was the invention of the null reference in 1965… My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
– Tony Hoare
Nulls are terrible. They’re dangerous and sneaky and they’re why Java’s type system is unsound. Ideally, we’d never use them, but we can’t do much about twenty years of libraries which might return nulls. At least we can try to stop returning them in our own APIs, because Java 8 gave us Optional
s.
What’s an Optional
? It’s a data type which represents either a value, or… not a value. This allows us to represent the possibility of an absence of the value in the type system. So, instead of code like this:
public static void helloKitty(Cat kitty) {
if(kitty != null) {
System.out.println(kitty.meow());
}
}
We can write code like this:
public static void helloKitty(Optional<Cat> kitty) {
if(kitty.isPresent()) {
System.out.println(kitty.get().meow());
}
}
The latter code is, to my mind, indisputably better than the former. The possibility of nullity is encoded in the types, and we can’t do anything to the cat without making a conscious decision to remove it from the Optional
.
Intent is clearer. Mistakes are less likely. These are good things.
That said, don’t write code like this. Just because it’s better than the null-exposed version doesn’t make it good.