4 ms·
I don't agree with returning anywhere; I think it's important to "return" exactly once, and that includes not using "break", "continue" and "goto" to perform lo
by makecheck 16y ago
I don't agree with returning anywhere; I think it's important to "return" exactly once, and that includes not using "break", "continue" and "goto" to perform logical short-cuts in most cases. (I've been writing code for 20 years.)
One reason is to have result or loop variables, which help debugging. You can ask debuggers to watch the value change, or print it, and so forth. Almost always create variables; ignore premature-optimization "experts" who think they've sped stuff up because they used fewer variables.
Cleanup isn't repeated. I despise "hunting" for return statements to ensure the same 3 things always happen. Yes, maybe functions shouldn't do so much; but if you're stuck maintaining something you didn't write, you still have to be able to apply a change correctly.
Another problem with multiple returns is inconsistent types. I've seen code where one person did "return false" and another did "return 1.0" in the same function; whereas, if you're forced to type "isOK = 1.0", you'll see the problem immediately.
And a single return point keeps overly-complex logic in your face, so that you have good incentive to fix it. You're less likely to put off refactoring an ugly and oversized function if you keep having to scroll through it to figure out what a single case is doing. Less code is ultimately good for maintainability.
- bborud 16y agoI was exposed to the "single return" philosophy some time in the mid 80s and for some years I applied it dogmatically to most of my code. However, at some point I started looking at the resulting code and re-evaluating "why am I doing this". Now, an important point is that I use different languages these days than I did in the 80s. Also, back then I didn't write a lot of (or any?) concurrent/asynchronous code, so the programming style was far more linear and synchronous. The things that applied to my 1980s Pascal or C programs are not necessarily true for my Java/Groovy/C/C++ programs today.