3 ms·
This makes sense only when you have to have an explicit return point. In languages that return the last expression, I find it much more palatable to represent y
by shadowfiend 9y ago
This makes sense only when you have to have an explicit return point. In languages that return the last expression, I find it much more palatable to represent your conditions as top-level if expression.
A conversion of the base example would be:
function () {
if () {
x
} else {
if () {
y
} else {
z
}
}
}
Granted it's also worth noting in such a language I rarely find myself using `if` and `else`. More likely I'm doing flow control based on `map` and some version of `getOrElse` (Scala's term for Option that allows you to return an existing value or alternate to a nonexistent value). These abstractions tend to compose better, and lead to more clarity as to what particular data item is leading to the value being one thing or another; e.g.:
function() {
requestValue orElse sessionValue getOrElse defaultValue
}
If requestValue is defined, return it; otherwise, if sessionValue is defined, return it; otherwise, return defaultValue. While not all conditions are immediately expressed this way, many of them can be simplified to data flow decisions that can be expressed this way, and the exercise of reworking the solution to use this strategy clarifies the surrounding program as well.