Safe Navigation Operator “?.” for D2 ?

SomeDude lolilol at mytrashmail.com
Fri Feb 28 19:40:51 PST 2014


On Friday, 28 February 2014 at 11:21:47 UTC, Marc Schütz wrote:
> On Friday, 28 February 2014 at 11:11:28 UTC, Dicebot wrote:
>> On Friday, 28 February 2014 at 09:24:23 UTC, John Colvin wrote:
>>>> Chaining . operation is a code smell to begin with
>>>
>>> It is? Why?
>>
>> If a system is well-designed, then "null" state either means 
>> something (and needs to be explicitly handled) or is not 
>> possible.
>>
>> ?. provides simple and easy way to write a sloppy code that 
>> does not tell the reader if resulting code flow for null case 
>> was intentional. Also it is very easy to get accustomed to use 
>> ?. everywhere instead of . and get broken logic instead of 
>> NullPointerException for cases when pointer is wrongly assumed 
>> to never be null.
>
> I sometimes come across situations like this:
>
> writeln_or_whatever(person ? person.name : "");
>
> (This is a case of "means something".)
>
> Using `person?.name` is a bit shorter and DRYer. But it would 
> be more useful if I could specify the default value it returns. 
> With an explicit `maybe` this would be possible:
>
> person.maybe("<n/a>").name;

I am also on the opinion that chaining on nullable objects
encourages sloppy code and should therefore be avoided. Because
the null case should often be handled. Chaining skips handling
the null case. Thus this syntaxic sugar is a bad idea.

The chaining pattern is okay to make code more expressive, but it
is always assumed that the objects on which it's applied are
non-nullable.


More information about the Digitalmars-d mailing list