Re:Comparing the Same Project in Rust, Haskell, C++, Python,...
by Krssst on Sunday June 16, 2019 @03:22AM
(#20194302)
Nested ternary operators are hardly ever a good idea.
Would using ternary operators as a terser switch statement be fine?
int a =
b == 1 ? 2 :
b == 2 ? 3 :
b == 3 ? 5 :
-1;
Re:Comparing the Same Project in Rust, Haskell, C++, Python,...
by masklinn on Sunday June 16, 2019 @04:17AM
(#20194446)
I like those, but they do need to be properly formatted and only "tail-nested".
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.
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.