Quantcast
Channel: What are pros/cons of ternary conditional operators? - Programming Language Design and Implementation Stack Exchange
Viewing all articles
Browse latest Browse all 10

Answer by FireTheLost for What are pros/cons of ternary conditional operators?

$
0
0

Con: Can lead to unreadable code

The syntax of ?: is pretty unintuitive. Python's X if Y else Z is slightly better. However, this problem becomes worse if many such if-else expressions are nested. For example, (a) ? (b ? c : d) : (e ? f : g) or even the following where it is easy to see what the code does but may be difficult to reason about how it does it:

String result = a ? "A" :                b ? "B" :                c ? "C" :                d ? "D" :                e ? "E" :                f ? "F" :                g ? "G" :                h ? "H" :"I";

Though these examples are contrived, they show how ternary operators can lead to unwieldy code pretty quickly. Ternary operators are good for short conditional expressions; for larger conditions, if-else statements are better.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>