5 ms·
I've never been a fan of the "only one return" view. I find it far easier to understand when the "preconditions" are checked at the beginning of the function an
by RHSeeger 5y ago
I've never been a fan of the "only one return" view. I find it far easier to understand when the "preconditions" are checked at the beginning of the function and, if they fail, bail out early (guard clauses). Then there's less mental load in the rest of the function.
- jwalton 5y agoI do this too. :P Especially in a language like Go or C where you don't have exceptions, I think the "fast fail" at the start of the function is a reasonable "exception to the rule". Otherwise you can quickly end up in a nested if statement hell. But back in the days when I was doing embedded work, I frequently came across problems where someone allocated some resource at the start of a function, freed the resource at the end of the function, but then either failed to realize there was a return in the middle of the function, or someone else came along later and added a return to the middle of the function; either way we ended up with a resource leak. I saw this pattern over and over again. "Fast fail" is reasonable design pattern, so long as it's at the top of the function and you're careful not to allocate things before you check for preconditions, but functions of the form: blah blah if blah blah return x else blah blah return y are (IMHO) an anti-pattern.
- Izkata 5y agoYeah, I'm pretty sure those leaks are the origin of it. At some point it became a "best practice" without understanding the reasons behind it, and people started applying it everywhere without any thought to "why".
- jonny_eh 5y agoThis has certainly become the the common best practice. I'm a fan too.
- twoodfin 5y agoI typically take this a step further, returning from trivial or common “fast-path” cases up front and falling through to any complex logic.
- deleted 5y ago[deleted]