4 ms·
Can someone older or wiser than me discuss what the idea is behind "only one return per method" in imperative code? I agree completely that it makes many metho
by mquander 15y ago
Can someone older or wiser than me discuss what the idea is behind "only one return per method" in imperative code? I agree completely that it makes many methods much more difficult to read, and I've never understood why it was taught as a guideline in the past (and why some people still seem to subscribe to it today.)
EDIT: It makes a lot more sense to me now that I think about it in the context of a language like C, with no garbage collection and no exceptions. Thanks!
- brnstz 15y agoIt was part of the structured programming dogma. One entry point, one exit point. Multiple return was lumped in with using goto. I never use goto, but I often use multiple returns similar to the examples in this article. I have sadly code reviewed many pieces of code with the nesting problem.
- malkia 15y agoif you have to use C++ without exceptions (console video games), then goto is much needed to handle exceptional situations locally. For example there would be label "fail:;" or "out:;" at the end of the function, where release of resource would happen, and you would "goto" to it, rather than releasing the resources in multiple exceptional places and return from there.
- brnstz 15y agoInteresting. I rarely program in an environment without exceptions, so I haven't had reason to adopt that style. I recall that Linus has advocated the use of goto in the Linux kernel for similar reasons. And the goto version of this code does seem more readable to me: http://kerneltrap.org/node/553/2131 http://kerneltrap.org/node/553/2131
- cpeterso 15y agoIf you are using C++ (even without exceptions), then RAII (Resource Acquisition Is Initialization) with resources freed in local variables' destructors is a better solution.
- __rkaup__ 15y agoWhy don't console games use exceptions?
- to3m 15y agoNo compiler support on one common system. You should be handling every case anyway - by the time the code is done, there are no exceptional situations left ;)
- kabdib 15y agoMakes maintenance simpler; any resource cleanup can go through one point and you can see that it is correct when modifications are made. (C++ gives this to you with destructors, mostly). Also makes it easier to step through code ("I'll just set a breakpoint and see what this function returns..."). I usually advocate using early returns for near boilerplate things like parameter checking, then a single return that does cleanup and exit, with 'goto' encouraged as the proxy for a return-in-the-middle. I think of it as similar to what a C++ compiler does for you. These days I code for maintenance, since someone /is/ going to go in and start adding early returns and subsequent bugs. Plan for code rot.
- ori_b 15y agoFar easier to do stuff like 'assert(postcondition)'