4 ms·
Seems to me that there is quite a bit of commentary on this subject, and you can find it by searching for its typical solution: guard clauses[1]. [1] http://wi
by citation_please 9y ago
Seems to me that there is quite a bit of commentary on this subject, and you can find it by searching for its typical solution: guard clauses[1].
[1] http://wiki.c2.com/?GuardClause http://wiki.c2.com/?GuardClause
- kdazzle 9y agoYeah, Swift in particular really embraces that pattern.
- masklinn 9y agoAlso functional languages with function guards e.g. while Erlang/Elixir does not have a return statement (and thus early return) you can write handle(Err, Results) when Err /= undefined -> handle_error(Err); handle(_, Results) -> % etc… . though errors would generally be reified as the ad-hoc union of two tuples and would look more like this: handle({error, Info}) -> handle_error(Info); handle({ok, Results}) -> % handle results .
- SideburnsOfDoom 9y agoThe functional style that you show certainly has multiple points where a value is returned, so you could call it "early return"; even if as a syntactic shorthand the keyword "return" is omitted. This is common across a lot of functional languages.
- masklinn 9y ago> The functional style that you show certainly has multiple points where a value is returned, so you could call it "early return"; It's not "early return" any more than: function(err, results) { if (!err) { // handle results } else { return handleError(err) } }
- SideburnsOfDoom 9y agoRight, though I was thinking of other examples of functional match style and returning a value. As seen in in Haskell, F# Rust etc. e.g. https://doc.rust-lang.org/book/second-edition/ch06-02-match.html https://doc.rust-lang.org/book/second-edition/ch06-02-match.... So value_in_cents can return a value of 1, 5, 10 or 25. Saying that it "does not have a return statement" might be truish - but the fact that the "return" keyword is not needed to return values is just syntax. Saying that there's no early return / multiple exit points is not so much. To my eye there are 4 places where that function can return a value. And the cases might not be simple numbers making the whole thing an expression, later examples on that page show how the cases can differ in side-effects.
- jwilk 9y agoCopy of the article, which doesn't require JS: https://gist.github.com/jwilk/6e7ecb94b623a82d01cdcd9765f05b4f https://gist.github.com/jwilk/6e7ecb94b623a82d01cdcd9765f05b...