View mode: basic / threaded / horizontal-split · Log in · Help
March 05, 2009
Re: Null references (oh no, not again!)
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.

Top | Discussion index | About this forum | D home