5 ms·
Maybe so, but what happens when you need to do something before returning the value, say like closing a connection? You'd have to make the change in 4 spots (an
by whileonebegin 14y ago
Maybe so, but what happens when you need to do something before returning the value, say like closing a connection? You'd have to make the change in 4 spots (and hope you don't miss one), as opposed to the first example where you'd only have to make the change in 1 spot. It's all about minimizing errors later on.
- MBlume 14y agoWrap in another function. ETA: I'm amused by how easily the LISP philosophy applies here: any problem can be solved with enough lambdas.
- fferen 14y agoI know, right? I was writing this complex OO solution to a problem in Python, then I realized I could just do it with a function returning a closure.
- bwh2 14y agoThen do something like hxa's example. Maintaining a return variable isn't always bad, it's just weird to think of it as functionally better than multiple returns. I tend to find a lot of errors and bugs in heavily nested code because it involves tracking a lot of variable state.
- SideburnsOfDoom 14y ago> Maybe so, but what happens when you need to do something before returning the value, say like closing a connection? Then your choices include a try...finally block, a "using" statement if you're in c#, or ... limiting yourself to only 1 return. Multiple returns don't fix the problems in all cases, just most of them. I'm assuming that this is on a language that has automatic garbage collection. The 1-return rule came about in C, which does not and so has a lot more cases where manual clean-up is required.