Null references (oh no, not again!)

Alex Burton alexibu at mac.com
Thu Mar 5 05:01:09 PST 2009


Walter Bright Wrote:

When I see code like this I see bugs.

> 
> Foo f;
> if (x < 1) f = new Foo(1);
> else if (x >= 1) f = new Foo(2);
> f.member();
> 

This should not compile IMHO default non nullable is necessary.
If using a language with default nullable, I would write this as 
Foo generateFoo()
{
    if (x < 1) return new Foo(1);
    else if (x >= 1) return new Foo(2);
}
This way the compiler has to check that there is a returned value for each path.
As the conditions become more complex, the compiler enforcing a return value prevents the result from being null (unless of course you return 0 just to prove a point)

> Foo f;
> bar(&f);
> 
> ? Or in another form:
> 
> bar(ref Foo f);
> Foo f;
> bar(f);
> 
> Java doesn't have ref parameters.

Same problem.
The prototype of bar should be Foo bar() if the intent of bar is to return a reference to an instance of Foo. Returning what is conceptually the result of a function in by ref parameters is really nasty way to code IMHO.

Alex




More information about the Digitalmars-d mailing list