I graduated in 1990 in Electrical Engineering and since then I have been in university, doing research in the field of DSP. To me programming is more a tool than a job.
Usually in this kind of things I have a pragmatic, almost obvious, approach: ternary operator is a tool that has its pros and cons, it has contexts where it is useful and contexts where you can use it, but it is quite a stretch...
It is true, however, that C-style ternary operator lacks somehow readability.
In Ada we have a kind of ternary operator too, but its syntax is (IMHO) much more readable
The (...) around the if and the case are mandatory.
I find it useful in simple contexts where a classical if ... then ... else would look redundant. It is fundamental in defining inline functions (I think it was the reason for introducing it)
and also in some pre/post condition. Suppose you have a function Foo that returns 0.0 when its argument is negative and a value larger than the input otherwise. You can write
Usually in this kind of things I have a pragmatic, almost obvious, approach: ternary operator is a tool that has its pros and cons, it has contexts where it is useful and contexts where you can use it, but it is quite a stretch...
It is true, however, that C-style ternary operator lacks somehow readability.
In Ada we have a kind of ternary operator too, but its syntax is (IMHO) much more readable
We have
case
too (switch
for you C people)The
(...)
around theif
and thecase
are mandatory.I find it useful in simple contexts where a classical
if ... then ... else
would look redundant. It is fundamental in defining inline functions (I think it was the reason for introducing it)and also in some pre/post condition. Suppose you have a function
Foo
that returns 0.0 when its argument is negative and a value larger than the input otherwise. You can writeAlso the implication A => B is nicely expressed with the ternary
I definitely agree that there is a time and a place for everything! I’ll still use ternary operators, just not as frequently!!
Thanks for the in depth breakdown, and thanks for reading!!!