by olavk · 8y ago · 0 comments
If the conditions are semantically symmetrical, if/else is the right approach:
fun max(a, b) {
if a > b { a } else { b }
}
But is it a precondition which causes you to skip the primary logic of the function, then get it out of the way early: fun max(a, b) {
// special case for null
if a==null or b==null { null }
if a > b { a } else { b }
}
Yeah we want to reduce indentation, but not at the cost of making the code overall harder to follow. The logic of "max" is much clearly expressed as a single expression with `else`.edit: now that I've looked through the comments I see these are mentioned on numerous other threads.
[0]: https://en.wikipedia.org/wiki/Guard_%28computer_science%29
Early returns are not a panacea. If/Else-everything is not a silver bullet either.
fun max(a, b) {
if a > b {
return a
}
return b
}
Not saying this is necessarily better or worse. The point I want to make is that your case isn’t special. if (x > y) {
return x;
} else {
return y;
}
if (x > y) {
return x;
}
return y;
return (x > y) ? x : y;
The logic would be convoluted if you are going through extra hoops in order to write your logic like this, making the flow of the application unclear. For some things, an else branch ends up just being easier to deal with. This is especially true in languages like Rust, where if/else is an expression, leading to the following construct being used often (although usually with more complicated content): let max = if (x > y) {
x
} else {
y
};
Note that "max" is immutable despite the conditional assignment due to the if being used as an expression.If it's a single line of return in both branches, then a ternary expression is usually going to be ideal instead.
foo(things) {
stuff = do_work(things);
if (stuff) {
return a;
} else {
return b;
}
}
into foo(things) {
stuff = do_work(things);
if (stuff) {
return a;
}
return b;
}
in code reviews.Ok, I really wonder if in this special case the logic just looks _odd_ because of bracing styles. (bear with me)
This is very easy to understand, where as the parent example, not as much.
fun max(a, b)
{
if a > b
{
return a
}
return b
}A max function is one of those rare moments where a ternary statement just seems right, but it's an admittedly simple example.
But if you are using a more imperative language where “if” is a statement, I think the merits of early return vs. use of an else clause are more balanced in this case.
return (a>=b) ? a : b
is probably the best option in those languages. The level of complexity at which the C ternary operator ceases to be ideal, I think, is lower than that of expression-if.