Michel Fortin wrote:
On 2009-09-26 23:28:30 -0400, Michel Fortin <michel.for...@michelf.com> said:

On 2009-09-26 22:07:00 -0400, Walter Bright <newshou...@digitalmars.com> said:

[...] The facilities in D enable one to construct a non-nullable type, and they are appropriate for many designs. I just don't see them as a replacement for *all* reference types.

As far as I understand this thread, no one here is arguing that non-nullable references/pointers should replace *all* reference/pointer types. The argument made is that non-nullable should be the default and nullable can be specified explicitly any time you need it.

So if you need a reference you use "Object" as the type, and if you want that reference to be nullable you write "Object?". The static analysis can then assert that your code properly check for null prior dereferencing a nullable type and issues a compilation error if not.

I just want to add: some people here are suggesting the compiler adds code to check for null and throw exceptions... I believe like you that this is the wrong approach because, like you said, it makes people add dummy try/catch statements to ignore the error. What you want a prorammer to do is check for null and properly handle the situation before the error occurs, and this is exactly what the static analysis approach I suggest forces.

Take this example where "a" is non-nullable and "b" is nullable:

string test(Object a, Object? b)
{
    auto x = a.toString();
    auto y = b.toString();
return x ~ y;
}

This should result in a compiler error on line 4 with a message telling you that "b" needs to be checked for null prior use. The programmer must then fix his error with an if (or some other control structure), like this:

string test(Object a, Object? b)
{
    audo result = a.toString();
    if (b)
        result ~= b.toString();

    return result;
}

And now the compiler will let it pass. This is what I'd like to see. What do you think?

I'm not totally against throwing exceptions in some cases, but the above approach would be much more useful. Unfortunatly, throwing exceptions it the best you can do with a library type approach.


I don't think this would fly. One good thing about nullable references is that they are dynamically checked for validity at virtually zero cost. Non-nullable references, therefore, would not add value in that respect, but would add value by reducing the cases when programmers forgot to initialize references properly.

Andrei

Reply via email to