Conditional logic is the third hardest thing just after variable naming and cache invalidation. There is no excuse to make it harder to understand.
Conditional logic is the third hardest thing just after variable naming and cache invalidation. There is no excuse to make it harder to understand.
const result = (() => {
if (!conditionA) return 'Not A';
if (conditionB) return 'A & B';
return 'A';
})();
Yes, I know, I "need" to use curlies. But there's really no reason why someone shouldn't be able to quickly make sense of this. The ternary, on the other hand, is unnecessarily cryptic.if condition {do_x()} else {do_y()}
Basically there's no need for line breaks between if/else, but also they decided not to add a ternary conditional operator.
if (condition) { do_x() } else { do_y() }
That's the JavaScript version of what you wrote, and it's nearly identical. JavaScript doesn't require line breaks. const x = cond1 ? a
: cond2 ? b
: c
becomes in Rust let x = if cond1 { a }
else if cond2 { b }
else { c }However, I’m not sure how this is supposed to be “written far more concisely”? It’s more verbose, involves more different constructs, more levels of indirection - pretty much for any definition of “conciseness“ I can think of, it is worse.
(The example is also a bit misleading, since the logic flow between the nested ifs and the chained ternaries are subtly different.)
In the provided example, const result = !conditionA ? "Not A" : conditionB ? "A & B" : "A";
is really equivalent to:
const result = null;
if (!conditionA) {
result = "Not A";
} else if (conditionB) {
result = "A & B";
} else {
result = "A";
}
which I don't think is that bad (look ma! no nesting!). You could also use a function, especially if the logic is too complex to flatten reasonably: function checkConditions() {
if (!conditionA) {
return "Not A";
}
// A is true from here onwards.
if (!conditionB) {
return "A";
}
// B is also true from here onwards.
return "A & B";
}
const result = checkConditions();That language doesn't have an "elseif", so you're actually writing the shorthand for
if(!a) {
...
} else {
if(!b){
...
} else {
...
}
}
Your point stands nonetheless. I just had to smile seeing that examplehttps://www.typescriptlang.org/docs/handbook/advanced-types....
I must say that I find those examples clearly express what is going on.
Also, about another poster's comment, while it may be true that for regular code needing this may be a sign that the code needs refactoring, for business logic this is not true. You may very well end up with "business logic code" where things like huge functions and long nested conditionals actually are the optimal way to express messy reality, and that trying to use refactoring methods like "put this into extra functions" actually increases complexity.