null [re: spec#]

Nick Sabalausky a at a.a
Sun Nov 7 12:28:52 PST 2010


"Simen kjaeraas" <simen.kjaras at gmail.com> wrote in message 
news:op.vls9bigxvxi10f at biotronic-pc.lan...
> Roman Ivanov <isroman.DEL at ete.km.ru> wrote:
>
>> I know what your mean, but the example is flawed:
>>
>> public void foo()
>> {
>>     if (m) {
>>          Object p = new Object();
>>          p.toString();
>>     }
>> }
>
> You misunderstand. The idea is this:
>
> void foo( ) {
>   Object p;
>   if ( m ) {
>     p = new Object( );
>     p.DoSomethingThatNeedsToBeDoneNow( );
>   }
>   // 20 lines of code here
>   if ( m ) {
>     p.doSomethingWeird( dataFromAbove );
>   }
> }
>

If you do that, then there's two possibilities:

A. You intended p to get inited on all code paths but forgot a codepath. 
With real init-checking the compiler will tell you and you can fix it. With 
D as it is, you're not informed at all, and you may or may not catch the 
problem before deployment. Obviously the former is better.

B. You *intended* p to not always be inited, in which case the correct code 
is this:

void foo( ) {
  Object p=null;
  if ( m ) {
    p = new Object( );
    p.DoSomethingThatNeedsToBeDoneNow( );
  }
  // 20 lines of code here
  if ( p != null ) {
    p.doSomethingWeird( dataFromAbove );
  }
}

And with by-default non-nullability and a good optional "Nullable" system, 
it would be something like this (Completely made-up syntax for 
"Nullable!Object", don't nitpick it), which would be far safer:

void foo( ) {
  Nullable!Object p=null;
  if ( m ) {
    p = new Object( );
    // Compiler knows p is really "Object" instead of "Nullable!Object"
    // from here to the end of scope, or until p is potentially reassigned.

    p.DoSomethingThatNeedsToBeDoneNow( );
  }

  // 20 lines of code here
  p.toString(); // Compile-time error, p might be null
  // 20 lines of code here

  if ( p != null ) {
    // Compiler knows p is really "Object" instead of "Nullable!Object" 
inside here
    p.doSomethingWeird( dataFromAbove );
  }
}





More information about the Digitalmars-d mailing list