One thing that people writing this sort of code seem to miss is that it's not just about expressing the code as concisely as possible - other people including oneself in future need to be able to read it easily.
What I would recommend in a code review for anyone using nested ternary operators is just to break them up using meaningful variable names so that you have one ternary operator per statement. It'll be easier to read and the names will help understand what's going on more easily.
Would using ternary operators as a terser switch statement be fine?
int a =
b == 1 ? 2 :
b == 2 ? 3 :
b == 3 ? 5 :
-1;I also tend to format them thus:
int a = b == 1 ? 2
: b == 2 ? 3
: b == 3 ? 5
: -1;
Feels much more "case analysis-y" and clearer.Still, a language having proper support for expressive conditionals is probably better.
Also the way Python's ternary was defined means it should never ever be nested, it looks nasty.
x = y ? 1
: 2;It's only the Algol-syntax-family languages (C, C++, Java, JavaScript, etc.) that have the inscrutable ternary operator and if/else as a statement.
It's a tricky problem to decide which idioms are most expressive/readable/maintainable as it's has a group dynamic. My rule of thumb, if I feel I've written clever code it's time to rethink approach.
var myvar = foo < bar
? bar
: bar < baz
? baz
: 0 const myvar
= foo < bar ? bar
: bar < baz ? baz
: lark < 10 ? lark
: 0 var myvar =
foo < bar ? bar :
bar < baz ? baz :
0
or: var myvar =
foo < bar ? bar
: bar < baz ? baz
: 0Something like
Screen.oled ? "black" : "rgb(21,21,21)"
is easy enough to read. Beyond that, if statements win for me.I don't think there's ever a good excuse for that much nesting of ternary operators.
* Lines of code
* # of keywords/operators
* # of non-standard keywords/operators (i.e. 'go' versus 'if')
* Use of std. library vs. 3rd party libraries
* Depth of call-stack, i.e. is it passing through 3 parent classes
if (x) {
y
}
else {
z
}
if x:
y
else:
z
Assuming x and y are 1 line but long enough expressions you don't want to use a trinary operator (available in both) the python is 2/3rds the length of the c because of bracketing. Obviously cherry picked, but I bet these differences add up.I wrote the style of C that I actually write, but it's probably not fair for me to label it as a property of just the language.