Null references redux

Michel Fortin michel.fortin at michelf.com
Sat Sep 26 20:45:35 PDT 2009


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

> On 2009-09-26 22:07:00 -0400, Walter Bright <newshound1 at 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.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list