5 ms·
Early returns are underrated.
by emilsedgh 7y ago
Early returns are underrated.
- skrebbel 7y agoThey sure are. I often extract logic into a function just so I can use early returns and have less local state. I mean, they're a recipe for disaster in C++, but I don't code much C++ anymore. In JS and similar-enough languages it's lovely.
- humanrebar 7y agoThey're fine in C++ given RAII guarantees. I feel safer using them in C++ than most other languages.
- falcrist 7y agoI typically code in c and c#, and have been told by older engineers that it's important to avoid early returns because they can be confusing, especially when skimming through the code. I kind of see what he's talking about. It seems like it's a little easier to reason with the code and easier to set breakpoints sometimes. All that's to say: I'm curious as to why early returns would be better in JS.
- hackinthebochs 7y ago>avoid early returns because they can be confusing It seems to me like the exact opposite is true. Early return conditions stand out in your code and so the structure matches the flow. Its much clearer than having error state weaved through the mainline behavior of the function. I'm pretty sure the pattern of having only one return is popular among older engineers because it makes it easier to use pre-condition/post-condition/invariant style reasoning which used to be popular. Outside of this scenario I see no reason to avoid early returns.
- Agentlien 7y agoWhat do you mean by "recipe for disaster"? I use them a lot in C++ and as long as you stick with RAII (which you really should), I don't see any language-specific problems with it.
- skrebbel 7y agoSure, if all the code you write and call into (OSS etc) is fully RAII then you're good. When I last did C++ for real, lots of code out there didn't meet that standard, not in the least libraries and vendor software, so more experienced programmers than me taught me to be better safe than sorry.