3 ms·
I used to use early returns a fair bit in Python and Ruby (my primary languages). But lately I've been working with Elixir which doesn't support early returns
by nickjj 7y ago
I used to use early returns a fair bit in Python and Ruby (my primary languages).
But lately I've been working with Elixir which doesn't support early returns and while Elixir does have some tricks up its sleeve to better handle the idea of having an early return without using it (such as pattern matching on function arguments and / or guards), I'm now slowly shifting into thinking early returns in any language makes things more difficult to reason about in the end most of the time.
I say "most of the time" because for very short functions where you might return early to avoid an else clause or deal with varying types of input, that's not too bad. It's really a problem in the use case you explained where you have a larger function that might have 4 or 5 early returns scattered about and that function might be nothing more than having a few short if statements that say "if this, then do_something and return". It becomes difficult to maintain because now the function ends in 5 different spots based on 5 different conditions.
- quadcore 7y agoAn interesting conjecture I've made during this discussion is the following: can early returns be responsible for over-engineered code? Think about it. If it's acceptable for programmers to use early returns then they can't stand bigger functions because those big functions systematically end up full of early returns. So programmers breaks things into small pieces instead, systematically. While there is many reasons why breaking things into small pieces could be the right thing to do, early returns is certainly not among them. You have to picture what I'm saying. What I'm conjecturing here is that many programmers simply can't make bigger functions so they'll take a battery of bad decisions, unconsciously, to avoid them. How big is that?