DEV Community

Why don't Python, Go and Rust have a ternary conditional operator?

豌豆花下猫 on April 05, 2023

Hello readers! This article is written by a Chinese author named 豌豆花下猫, who is writing his first English article with the super help of ChatGPT. I ...
Collapse
 
pinotattari profile image
Riccardo Bernardini

Two comments

  1. Ruby is another language where if (but also case) is an expression. Ruby has also (if I remember correctly) the classical C versiona ? b : c, this is aligned with the redundancy added to the language by design (another example is the length of an array: you can use size, length or count, as you like). I prefer the "if expression" solution: it is much easier to read than the cryptic a ? b : c.
  2. A language that choose the (if cond then A else B) format is Ada (together with the case expression too). It is a fairly recent addition (Ada 2002? 2012?) and I think it has been added motivated by its use in contracts (pre/post conditions), but I think it is popular also with inline functions.
  3. About the and/or ambiguity, Ada solves it by making parenthesis mandatory if a boolean expression has both and and or. Ada coders just hate (to be said with the voice of of the Grouchy Smurf 😏) ambiguous situations that could give rise to bugs.

On a personal level, I like the Ada solution: it is quite readable and in some context helps making the code clear by removing some scaffolding. Note the emphasis on some context: indeed, it is a construct that can be easily abused. I like the idea of having the possibility of choosing the form that I think it is more suited for every single case.

Collapse
 
chinesehuazhou profile image
豌豆花下猫

Thank you for sharing your knowledge.