Optional Types: ‘null’ without NullPointerException

Optional (nullable) types will be coming to JS++. This usually stokes fears of null pointer dereferencing. For example, in Java, this is known as a “NullPointerException”.

In fact, Turing Award winner Tony Hoare calls it his billion-dollar mistake:

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

However, it’s possible to have nulls in a language without ever having NullPointerExceptions.

void doStuff(Foo foo) {
    foo.bar(); // Error, potentially null
}

In the above example, foo can be either an instance of Foo or null at runtime. This creates the potential for dereferencing a null pointer. This is an easy fix though – we just check that foo is not null:

void doStuff(Foo foo) {
    if (foo != null) {
        foo.bar();
    }
}

By checking that foo is not null, we can guarantee foo is at least an instance of class Foo – thus making it very straightforward for us to check that the bar method exists. This is a process known as type refinement. What’s interesting is that the compiler is able to actually ensure you’ve made the check before you ever run your program. It achieves this by examining the control and data flow. This is cutting-edge research known as flow-sensitive type systems.

In addition, by examining the control and data flow, if we can ascertain that null was never passed into the doStuff function, type refinement would not need to occur, and you would not need to check for null. Thus, this code – with no null check – will still pass a compile:

void doStuff(Foo foo) {
    foo.bar();
}

doStuff(new Foo());

On the other hand, as soon as you introduce null, you need to check for null too:

// Attempt 1
void doStuff(Foo foo) {
    foo.bar(); // Error, 'foo' can be 'null'
}

doStuff(new Foo()); // ok
doStuff(null);      // now we need a null check
// Attempt 2
void doStuff(Foo foo) {
    if (foo != null) { // do the 'null' check so the code compiles
        foo.bar();
    }
}

doStuff(new Foo()); // ok
doStuff(null);      // ok

null is a first-class type in the JS++ type system so, combined with JS++’s sound type system, JS++ is able to categorically determine that you’ve checked foo is non-null without ever executing any code.