Null references redux

Walter Bright newshound1 at digitalmars.com
Sat Sep 26 15:03:40 PDT 2009


Denis Koroskin wrote:
> I don't understand you. You say you prefer 1, but describe the path D 
> currently takes, which is 2!
> 
> dchar d; // not initialized
> writeln(d); // Soldier on and silently produce garbage output

d is initialized to the "invalid" unicode bit pattern of 0xFFFF. You'll 
see this if you put a printf in. The bug here is in writeln failing to 
recognize the invalid value.

http://d.puremagic.com/issues/show_bug.cgi?id=3347

> I don't see at all how is it related to a non-null default.

Both are attempts to use invalid values.

> Non-null default is all about avoiding erroneous situations, enforcing 
> program correctness and stability. You solve an entire class of problem: 
> NullPointerException.

No, it just papers over the problem. The actual problem is the user 
failed to initialize it to a value that makes sense for his program. 
Setting it to a default value does not solve the problem.

Let's say the language is changed so that:

    int i;

is now illegal, and generates a compile time error message. What do you 
suggest the user do?

    int i = 0;

The compiler now accepts the code. But is 0 the correct value for the 
program? I guarantee you that programmers will simply insert "= 0" to 
get it to pass compilation, even if 0 is an invalid value for i for the 
logic of the program. (I guarantee it because I've seen it over and 
over, and the bugs that result.)

The point is, there really is no correct answer to the question "what 
should variables be default initialized to that will work correctly"? 
The best we can do is default initialize it to a NaN value, and then we 
can track usages of NaNs and know then that we have a program logic bug. 
A null reference is an ideal NaN value because attempts to use it will 
cause an immediate program halt with a findable indication of where the 
program logic went wrong. There's no avoiding it or pretending it didn't 
happen. There's no silently corrupt program output.



More information about the Digitalmars-d mailing list