4 ms·
Yes, the : and ? are single characters that are easily lost/overlooked among the rest of the code on that line. Even worse when there are nested ternaries.
by chihuahua 6y ago
Yes, the : and ? are single characters that are easily lost/overlooked among the rest of the code on that line. Even worse when there are nested ternaries.
- RHSeeger 6y agoWhen I find a place where a complex ternary is probably the best choice, I'm a big fan of the following format, because I find it clear that each line is a new condition myvar = condition_1 ? value_1 : condition_2 ? value_2 : condition_3 ? value_3 : value_fallback;
- dxdm 6y ago> where a complex ternary is probably the best choice Under what circumstances would that happen? I've never encountered a nested ternary that wouldn't be better replaced with readable code, so now I'm wondering what experiences I've been missing. :)
- kaoD 6y agoReadability is in the eye of the beholder.
- dxdm 6y agoYes, good point. Still, when working on a shared codebase, it's good to take more potential beholders into account. I suppose if there is a common, consistent style that you can expect everyone to be familiar with, you can get used to reading a sensible amount of chained ternaries.
- RHSeeger 6y agoI don't have an example handy, but it's useful in exactly the same cases where you would use a Lisp "cond" construct; testing a bunch of conditions one after the other. Using an "if / else if / ... / else" construct can do the same thing, but it can be less clear sometimes (both to intent and because it takes up more screen real estate, which makes understanding the overall code harder).
- Pxtl 6y agoAnd, to illustrate my point, hypothetical "if statement is also conditional expression" syntax, to illustate how much more readable "ifs" are than "?:": myvar = if(condition_1) {value_1} else if(condition_2) {value_2} else if(condition_3) {value_3} else {value_fallback};
- RHSeeger 6y agoWhile I agree that "if statements are expressions" is a nice feature, I disagree that your version is more readable. That being said, it's readable enough that, if the rest of my team preferred it, I'd be ok using it.