const assignments problem again

Jacob Carlborg doob at me.com
Tue Aug 9 00:01:35 PDT 2011


On 2011-08-09 07:04, Don wrote:
> Jacob Carlborg wrote:
>> On 2011-08-07 03:19, bearophile wrote:
>>> I have discussed about this topic once in past, but in the meantime I
>>> have seen this is a quite common problem, so I think it doesn't harm
>>> to touch this topic again.
>>>
>>> This is a direct D translation of the original C or C++ code:
>>>
>>>
>>> // version #1
>>> double foo;
>>> if (abs(e.x - v.x)> double.min)
>>> foo = (v.y - e.y) / (v.x - e.x);
>>> else
>>> foo = double.max;
>>
>> If D's statements were expressions instead, this could work:
>>
>> const foo = if (abs(e.x - v.x)> double.min)
>> (v.y - e.y) / (v.x - e.x);
>> else
>> double.max;
>>
>
> I find that much more difficult to read.
> Especially consider
>
> const foo = (a > b) ? bar() : baz();
>
> compared to
>
> const foo = if (a > b)
> bar();
> else
> baz();
>
> You have to read quite a lot of code before you get any visual cue that
> the return value of baz() is used.
> IMHO: to understand code, I think you really need to know if you're
> looking at an expression or a statement, so making 'if' do both jobs
> reduces code clarity. (Would be OK in a language where it was _always_
> an expression).

I think this syntax fits when using a ternary operator would be too long 
and creating one (or two) new function(s) would just be annoying. But if 
the if-statement wasn't an expression in all cases it would be very 
confusing. I see no reason why many of the statements in D couldn't be 
expressions instead, but I can understand that it's way too late to 
change that now.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list