Austin Z. Henley

Assistant Professor


Home | Publications | Teaching | Blog | CV

Is optional null better?

9/4/2019

There is a lot of disdain for null in programming languages. Tony Hoare has famously called it his billion dollar mistake and plenty of others have stated how evil null is.

In response, there has been a movement for languages to make reference types non-nullable by default. (I'm going to call this optional null for brevity.) For example, Swift and Kotlin as well as upcoming versions of C# and Dart make it so that reference types can't have null values unless explicitly allowing for it.

It looks like this:

    Item? item; // Can be null!
    Group group = new Group(); // Can't be null!
    Dictionary<int, string>? lookup; // Can be null!

Placing a question mark after the variable's type indicates that the variable can be null. Without it, it cannot be null.

But given all the standard arguments against null and the problems it causes, is this optional null much of an improvement?

The benefit of optional null is that you can explicitly express when null should or should not be allowed. Kind of like const by default, the type checker is now helping you. You won't have a pesky null value showing up when you think it isn't possible and you can remove null checks that are littering your code since it can't happen.

So what are the potential downsides?

I'm just now starting to use optional null so I'm unsure what I will think of it in a year. At the moment I don't see it solving my problems. If only I could get rid of null entirely!