Sujet : Re: Command Languages Versus Programming Languages
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.unix.shell comp.unix.programmer comp.lang.miscDate : 06. Apr 2024, 15:44:13
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <uurjjf$2409m$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
User-Agent : Mozilla Thunderbird
On 06/04/2024 03:01, Kaz Kylheku wrote:
On 2024-04-05, Alan Bawden <alan@csail.mit.edu> wrote:
Lawrence D'Oliveiro <ldo@nz.invalid> writes:
>
On Fri, 5 Apr 2024 09:17:37 -0000 (UTC), Muttley wrote:
...
>> a =
>> b ?
>> c ? d : e
>> : f ?
>> g ? h : i
>> : j;
>
> Just use brackets. Saves a lot of pain.
>
a=(b?(c?d:e):(f?(g?h:i):j));
>
A normal programmer would write something like:
>
a = b ? (c ? d : e) :
f ? (g ? h : i) :
j;
>
I.e., she would allow herself to use spaces and newlines, and just
enough parentheses to make the structure clear.
It looks good, undeniably.
However, I cannot tell at a glance whether or not the nice appearance
isn't telling me some kind of lie. That's an inherent problem with
the ternary operator.
That's a key point - and it is not just with the ternary operator, but a general issue. Good spacing, indentation, newlines and layout make code easier to read. But it is vital that there is never any doubt that the layout matches the meaning of the code. If not, then you might be sure what the programmer meant dues to the layout, but you are not sure that the compiler sees it the same way. After all, this looks neat and clear too :
a =
b & c +
d & e +
f & g
But the language viewpoint (assuming it is in C, or a language with similar precedences) and the code appearance are very different.
Parentheses help, until there are too many to be easily tracked by the reader. Splitting the expression into parts, adding new local variables, using separate statements, making new helper functions - these are all ways to improve the code, and have no efficiency cost with modern tools.
A lot of people think the layout of code should make the programmer's intentions clear, and make it easy to see what the code does. That's true, but it is not enough. Code layout should also make it easy to see that the code does what the programmer intended. It should be easy for a maintainer to modify it without introducing errors. It should also be hard for a reader to misinterpret it (which is not the same as saying it should be easy to interpret correctly). It should be hard for a maintainer to make mistakes. It should be easy to spot any mistakes that get made.
I have to remember that = has lower precedence than ?:. But, ==
has higher precedence. So this careless edit makes it wrong,
even though it still looks just as nice:
a == b ? (c ? d : e) :
f ? (g ? h : i) :
j;