Nullable or Optional? Or something else?

Rainer Deyke rainerd at eldwood.com
Tue Sep 8 12:50:15 PDT 2009


Steven Schveighoffer wrote:
> Why do you care if it was or was not found in the configuration file
> beyond the call to retrieve it?  Pass in a default value (of null if you
> wish), or have the function return a separate boolean indicating whether
> it was found or not.

Yes, in this particular case, passing a default value would work just as
well.  But what if you want to cache the contents of the entire
configuration file?  What if calculating the default value is an
expensive operation that should be avoided if possible?

My argument isn't about any specific example.  My argument is that
inconsistent behavior in corner cases is the bane of good programming.

>  Using a new type just to determine if something
> was found during a function call seems like a waste to me.  If there's a
> reason to store that fact beyond the function call, then create a new
> type which stores that fact.

I thought the whole point of the Optional library type was to remove the
need for user-defined types consisting of a boolean and a T, where the T
is only valid if the boolean is 'true'?  If the real answer is to write
a new, different type, why have Optional at all?

> What do you think is more confusing?
> 
> auto val = getConfig("upperlimit")
> if(val is null)
>   upperLimit = default_upper_limit;
> else
>   upperLimit = *val;

Not confusing.

> upperLimit = getConfig("upperlimit", default_upper_limit);

Also not confusing, but different.  'default_upper_limit' is evaluated
even if the value is found in the configuration file.

>> No, keeping the container and the containee separate leads to /clearer/
>> (if slightly more verbose) syntax.  My proposal is to use use pointer
>> syntax:
>>   Optional!T v;
>>   f(v); // Do something with the container.
>>   f(*v); // Do something with the containee.
> 
> Hm... that means you have to use *v every time you want the value, and
> just v if you want to check for null?  I think the most common case is
> using the containee, I'd rather have that be the default.

You can't have that, because 'v' is already the container.  The best you
can get is a proxy that sometimes acts like a containee, but really
isn't.  This kind of sloppy thinking has no place in computer programming.


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list