DEV Community

Discussion on: Why I'm phasing out ternary statements

Collapse
 
pinotattari profile image
Riccardo Bernardini • Edited

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

   X := (if Test then Value_True else Value_False);

We have case too (switch for you C people)

Hours := (case D is
               when Mon .. Thurs => 8,
               when Fri => 6,
               when Sat | Sun => 0);

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)

  function Modulus(x : float) return Float
  is (if X >= 0.0 then X else -X);

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

  function Foo(X :Float) return Float
  with Post => (if X <0 then Foo'Result = 0.0 else Foo'Result > X);

Also the implication A => B is nicely expressed with the ternary

   (if A then B)
Collapse
 
mcgurkadam profile image
Adam McGurk

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!!!