Null references redux

Denis Koroskin 2korden at gmail.com
Sat Sep 26 15:49:16 PDT 2009


On Sun, 27 Sep 2009 02:43:05 +0400, Denis Koroskin <2korden at gmail.com>  
wrote:

> On Sun, 27 Sep 2009 02:18:15 +0400, Walter Bright  
> <newshound1 at digitalmars.com> wrote:
>
>> Denis Koroskin wrote:
>>>> If you disallow null references what would "Object foo;" initialize  
>>>> to then?
>>> Nothing. It's a compile-time error.
>>
>> Should:
>>
>>     int a;
>>
>> be disallowed, too? If not (and explain why it should behave  
>> differently), what about:
>>
>>     T a;
>>
>> in generic code?
>
> Functional languages don't distinguish between the two (reference or  
> not). We were discussing "non-null by default"-references because it's  
> far less radical change to a language that "non-null by default" for all  
> types.
>
> Once again, you are taking code out of the context. It is worthless to  
> discuss "int a;" on its own.
> I'll try to but the context back and show a few concrete examples (where  
> T is a generic type):
>
> void foo()
> {
>      T t;
> }
>
> Results in: error (Unused variable 't').
>
> T foo(bool someCondition)
> {
>      T t;
>      if (someCondition) t = someInitializer();
>
>      return t;
> }
>
> Results in: error (Use of potentially unassigned variable 't')
>
> T foo(bool someCondition)
> {
>      T t;
>      if (someCondition) t = someInitializer();
>      else t = someOtherInitializer();
>
>      return t;
> }
>
> Results in: successful compilation

One more:

T foo(bool someCondition)
{
     T? t;
     if (someCondition) t = someInitializer();
     // ...

     if (t.isNull) { // not initialized yet
         // ...
     }

     return enforce(t); // throws if t is not initialized yet, because foo  
*must* return a valid value by a contract
}



More information about the Digitalmars-d mailing list