Search code examples
language-agnosticnulllanguage-designnullable

Should References in Object-Oriented Programming Languages be Non-Nullable by Default?


Null pointers have been described as the "billion dollar mistake". Some languages have reference types which can't be assigned the null value.

I wonder if in designing a new object-oriented language whether the default behavior should be for references to prevent being assigned null. A special version of the could then be used to override this behavior. For example:

MyClass notNullable = new MyClass();
notNullable = null; // Error!
// a la C#, where "T?" means "Nullable<T>"
MyClass? nullable = new MyClass();
nullable = null; // Allowed

So my question is, is there any reason not to do this in a new programming language?

EDIT:

I wanted to add that a recent comment on my blog pointed out that non-nullable types have a particular problem whenb used in Arrays. I also want to thank everyone for their useful insights. It is very helpful, sorry I could only choose one answer.


Solution

  • The main obstruction I see to non-nullable reference types by default is that some portion of the programming community prefers the create-set-use pattern:

    x = new Foo()
    x.Prop <- someInitValue
    x.DoSomething()
    

    to overloaded constructors:

    x = new Foo(someInitValue)
    x.DoSomething()
    

    and this leaves the API designer in a bind with regards to the initial value of instance variables that might otherwise be null.

    Of course, like 'null' itself, the create-set-use pattern itself creates lots of meaningless object states and prevents useful invariants, so being rid of this is really a blessing rather than a curse. However it does affect a bit of API design in a way that many people will be unfamiliar with, so it's not something to do lightly.

    But overall, yes, if there is a great cataclysm that destroys all existing languages and compilers, one can only hope that when we rebuild we will not repeat this particular mistake. Nullability is the exception, not the rule!