Billion dollar mistake

Amit Sharma
3 min readAug 26, 2020

--

nulll is very familiar to all java developers and it is being treated as a great invention for a particular problem, and the problem is how would you define an “undefined”.

When there is no value to present how would it be presented ? The answer is “null” probably, I am not sure. ☹

Lets consider this :

The undefined has been in existence since the creation of coding, null is the misguided invention of British computer scientist Tony Hoare (most famous for his Quicksort algorithm) in 1964, who coined his invention of null references as his “billion dollar mistake”

And here is what he said :

I call it my billion-dollar mistake…At that time, I was designing the first comprehensive type system for references in an object-oriented language. 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, inventor of ALGOL W.

What is wrong with NULL?

The short answer: NULL is a value that is not a value. And that’s a problem.

The old way

Let’s consider this code:

This can obviously break with NullPointerException if any term is null.

A typical way of avoiding this:

Oh God ☹

This won’t explode, but is just ugly, and it’s easy to avoid some null check.

Let’s try with Java 8’s Optional:

Good 😊 but is it best 😕

As noted in a lot of posts, this isn’t a lot better than null checks. Some argue that it makes your intent clear.

I don’t see any big difference, most null checks being pretty obvious on those kind of situations.

Ok, let’s use the functional interfaces and get more power from Optional:

flatMap() will always return an Optional, so no nulls possible here, and you avoid having to wrap/unwrap to Optional.

Please note that I added *Optional() methods in the types for that. There are other ways to do it (map + flatMap to Optional::ofNullable is one). The best one: only return optional value where it makes sense: if you know the value will always be provided, make it non-optional. By the way, this advice works for old style null checks too.

ifPresent() will only run the code if it’s there. No default or anything.

Let’s just use member references to express the same in a tight way:

Or if you know that Project has an ApplicationType anyway:

Great 😊

Conclusion

By using Optional, and never working with null, you could avoid null checks altogether. Since they aren’t needed, you also avoid omitting a null check leading to NPEs. Still, make sure that values returned from legacy code (Map, …), which can be null, are wrapped asap in Optional.

--

--

Amit Sharma

IT Professional, Nature Lover, Defense & Technology Enthusiastic