null [re: spec#]

Nick Sabalausky a at a.a
Sun Nov 7 12:56:38 PST 2010


"Simen kjaeraas" <simen.kjaras at gmail.com> wrote in message 
news:op.vltiombuvxi10f at biotronic-pc.lan...
> Nick Sabalausky <a at a.a> wrote:
>> 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 );
>>   }
>> }
>
> There is a third option, wherein the if condition will only be true if
> p !is null, but the actual condition is more complex:
>
> if ( m > 4 ) {
>     p = new Object( );
>     p.DoSomethingThatNeedsToBeDoneNow( );
> }
>
> // code
>
> if ( m > 12 ) {
>     p.doSomethingWeird( dataFromAbove );
> }
>

- if ( m > 12 ) {
+ if ( p && m > 12 ) {

And you can toss in an "if(m>12) assert(p);" if you're worried about that.




More information about the Digitalmars-d mailing list