Pluggable type sytems

Bartosz Milewski bartosz at relisoft.com
Sun Feb 8 14:19:55 PST 2009


I also believe that non-null should be the default. Most references in a typical program are assumed to be non-null. 

Like for every default, there should be an escape mechanism from it. However, adding "nullable" to the type system might be controversial, especially because it requires special treatment of constructors and polymorphism (hence additional type modifiers, raw and poly-null, and I haven't even mentioned wildcard annotations).

So some time ago I came up with a more modest proposal. The compiler should catch nullable references at their source. It should enforce what I call "declaration is initialization" (DII). For instance, the following is correct:

Foo foo = new Foo;

and the following is not:

Foo foo; // error
...
foo = new Foo;

Obviously this rule is too strict, so there must be a way to override it. Here's the simple syntax:

Foo foo = null; // not an error!

Notice that the programmer explicitly states that one should be careful when using foo, because it might be null. 

Since this solution doesn't involve the type system, the nullability doesn't propagate across function calls. But it might be a tradeoff worth taking, if only for the simplicity.

Constructors still need some special treatment. Every class member variable must be initialized in the constructor. Again, the escape is to _explicitly_ initialize it to null. This might seem redundant, since the variable is already default initialized to null, but the compiler can easily eliminate such redundancies. 

I also found out that Java's editor, Eclipse, enforces DII--a very useful feature that paid off for me in the first 100 lines of code I wrote after a long period of inactivity in Java ;-) 

> Michel Fortin Wrote:

> In fact, I'd even argue that non-nullability should be the default for 
> pointers and class references, because it is either safer (if the 
> compiler doesn't do the null check for you) or less troublesome to use 
> (if the compiler forces you to check for null everytime). Another 
> reason being consistency: value-types can't be null by default and so 
> should be class references and pointers. And making pointers 
> non-nullable by default can only be done at the language level, so 
> obviously it's better in the language than as a user-defined type 
> modifier.




More information about the Digitalmars-d mailing list