4 ms·
I think the problem with #5 is the formatting and use case. Ternaries are really useful for certain things and can make code much easier to read but they are al
by jacoblambda 7y ago
I think the problem with #5 is the formatting and use case. Ternaries are really useful for certain things and can make code much easier to read but they are also super easy to misuse. The big thing I find is that ternaries allow for greater code density and better alignment of similar elements.
The style I find works best is as follows. Note that alignment of the ? and : characters (and depending on the code style, the parentheses) is vital for the legibility of this style.
x = (condA) ? (trueA) : (falseA)
(condB) ? (trueB) : (falseB)
(condC) ? (trueC) : (falseC)
(condD) ? (trueD) : (falseD)
(condE) ? (trueE) : (falseE)
: (final case);
Mind you this has it's uses mostly in low level stuff but I find it a hell of a lot easier to read than a giant if else chain.
- julienreszka 7y agoyes
- setr 7y agoIf I'm reading it right, those false cases shouldn't exist; it should be: x = (condA) ? (trueA) : (condB) ? (trueB) : (condC) ? (trueC) : (condD) ? (trueD) : (condE) ? (trueE) : (final case); and the equivalent if/else chain should be: if (condA) {x = trueA } elif (condB) {x = trueB } elif (condC) {x = trueC } elif (condD) {x = trueD } elif (condE) {x = trueE } else {x = (final case) } In which case it doesn't really get you much readability-wise, since the formatting consistency appears in either case; the main benefit really is that ternary is an expression rather than a statement It’s definitely superior, since it’s still less noise all around, but almost worthlessly so. And then the same pattern gets covered by switches too...
- jacoblambda 7y agoYep I'm dumb. That's what I get for writing that snippet last night with a few drinks in me. As for comparison against switches, I find that switches are very limited in a lot of languages (looking at you C/C++). The problem with the if else chain as well is that most code formatters seem to blow it up into the fully expanded form which kills readability.