Austin Z. Henley

Assistant Professor



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?

  • It makes the language more complicated. Probably a minor issue, but I have seen quite a few Stack Overflow questions about unwrapping optionals in Swift. Similarly, some of the early C# examples look hideous.
  • If I was using null as a corner case or error, then I now need a new way to represent this. I could wrap my reference objects in a Tuple and pass some sort of error object with it that I check in the relevant locations... exactly like I was doing with null. At least now the error has contextual meaning associated with it, unlike null.
  • I rarely have issues with null. Why are we still discussing this?
  • There are plenty of situations where I [think] I need null. This won't help with that, obviously, so the problem of null still remains.

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!