I’ve been primarily doing Elixir development for the past 6 years or so, and during that time whole heartedly committed to functional paradigms.
But recently I did some Go programming, and I hate to admit it, but working with early returns again was kinda nice.
I’m not a fan of lots of small little functions, and using
with seems to necessitate that; a lot of the times I’ll just deal with
So one day, I threw (pun intended) in the towel and refactored a plug that has many success cases as well as error cases that need to return early, to use
throw/catch to emulate early returns… and I was really happy with the results.
But there is this nagging feeling that I’ll be excommunicated from the community if this code ever sees the light of day publicly. I kid, I kid…
So why are early returns bad? I’ve since wrapped up the throw/catch paradigm into a tiny library that let’s it be used like this:
v = returnable do if some_condition?() return "foo" end ... end
I understand that early returns make mechanical “refactor into function” difficult, but I think wrapping it up in an expression like above negates the issue. Not sure.
I’ve seen some posts (on Reddit, not here) where people suggest you can use throw/catch to emulate early returns “but you need to be an expert to do it safely and properly.” Why is that? What pitfalls are they alluding to?
As always, thanks for the help and info!
P.S. A little further in that video, he describes a
use block that he wishes existed, but doesn’t know any programming language that has something like. I’m nearly positive it can be accomplished with metaprogramming in Elixir… but probably a topic for a separate post.