Wednesday, December 30, 2009

The problem with null pointers is that they are too darned useful

It would be nice if null pointers could be eliminated from the language, or at least integrated into the type system in a way that allows null pointer dereferences to be detected in advance. Unfortunately, 'null' tends to get used a lot - it's a great sentinel value for lazy construction, for example. So far all my ideas for making null type-safe also have the side-effect of making the code more complex and verbose.

Right now, the Tart compiler treats the value 'null' as a distinct type 'Null' (which is different from 'void'). You can compare any pointer or object reference with Null, but you can't assign Null to a variable of reference type. What you can do, however, is create a union of type 'SomeType or Null'.

var n:SomeType or Null = null;

In C++, if we wanted to lazily construct 'n', we'd write something like this:

if n == NULL {
  n = new SomeType();
}
      
return n;

However, this won't work in Tart because the final 'return n' returns a 'SomeType or Null', when what we want for it to return is 'SomeType'.

We could put an explicit type cast, except that in Tart type casts are always checked - which means that we're checking for null twice.

Another way to do this in Tart is to use the classify statement:

classify n {
  as r:SomeType { return r; }
  else {
    let r = SomeType();
    n = r;
    return r;
  }
}

This works, but seems fairly clumsy by comparison to the C++ version.

--
-- Talin

No comments:

Post a Comment