4 ms·
If you even need to indent them then why you don't write a full if else statement instead? Nested ternaries shouldn't be used at all.
by demo123 7y ago
If you even need to indent them then why you don't write a full if else statement instead? Nested ternaries shouldn't be used at all.
- _bxg1 7y agoFor languages in which if/else is unfortunately only imperative, not an expression
- _bxg1 7y agoIMO if if/else can be used as an expression, your language shouldn't have a ternary operator at all
- josephg 7y agoIf/else chains are worse because they allow problems like this: if (cond) { var1 = x; } else if (cond2) { var2 = y; } else { var1 = z; } Did you notice the second block assigned to var2 instead of var1? Best case it’s a gotcha for anyone reading the code later. It might be a bug by the original author; we can’t tell at a glance if this behaviour was intentional. Ternaries remove this problem. The intent of the author is clearer, and (with proper formatting) there’s no gotchas for anyone reading the code later.
- _bxg1 7y agoIf I understand correctly, what you're really advocating isn't ternary vs if/else, but expressive conditionals vs imperative conditionals. A statement that is something vs a statement that does something. Using expressions instead of imperative code that mutates state is a staple of functional programming, and is basically always preferred where possible. In some languages you can do this: var1 = if cond { x } else if cond2 { y } else { z } Which in my opinion is strictly better than using a ternary, if the language supports it.
- josephg 7y agoYes exactly. I mentioned in another comment that rust allows this, and having used it I think the best of all worlds. My favorite part is that its easy to add extra statements into the conditional blocks if you want. Doing that with ternaries requires either using the comma operator, repeating the condition on another line or refactoring the whole expression back out into if-else chains. All of those options are bad.
- macspoofing 7y agoTrue. When in Java, I've gotten into the habit of using the final initializer to mitigate these kinds of issues, like this: final T var1; if (cond) { var1 = x; } else if (cond2) { var2 = y; } else { var1 = z; } In this specific case, the compiler will catch the lack of initialization in the second block. It's also very helpful with a complicated/nested conditionals to guarantee that you initialize the variable through every code path.