5 ms·
I've been taught by some pretty experienced engineers that in terms of readability, multiple return statements are a bad idea. Instead, you should conditionally
by chatmasta 14y ago
I've been taught by some pretty experienced engineers that in terms of readability, multiple return statements are a bad idea. Instead, you should conditionally set a return variable, and return it once at the end of the function. But I'm not sold.... what is HN's thought on this matter?
- jbooth 14y agoWith go's defer mechanic (defer f.Close(), defer l.Unlock()), and the way they handle errors, multiple returns are basically the way code comes out naturally. I think it's more readable than juggling a bunch more variables and returning at the end, others may disagree.
- ihsw 14y agoUse guard clauses[1]. [1] http://martinfowler.com/refactoring/catalog/replaceNestedConditionalWithGuardClauses.html http://martinfowler.com/refactoring/catalog/replaceNestedCon...
- Jabbles 14y agoGo discourages it http://golang.org/doc/effective_go.html#if http://golang.org/doc/effective_go.html#if I think a blanket ban on multiple return locations is silly, as they can often be used to simplify code. There may be times when setting a return value is preferable, and I think you should use your judgement there. http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement http://stackoverflow.com/questions/36707/should-a-function-h...
- dscrd 14y agoOnly a sith etc etc. Like just about every other blanket statement about programming, this also is sometimes true and sometimes not. I find that multiple return statements in a function are more often a symptom of ugly code instead of the reason.
- genwin 14y agoI used to follow a bunch of best practices like this, that I now often find to be of too little benefit. If the function is small, multiple return statements won't significantly affect readability and it's simpler to code.
- igouy 14y ago>> If the function is small << And if the function is not small?
- mseepgood 14y agoThen extract functions until it's small, a.k.a. refactoring.
- marshray 14y ago...and if you end up needing to pass 20 variables via reference for state?
- masklinn 14y agohttp://www.refactoring.com/catalog/introduceParameterObject.html http://www.refactoring.com/catalog/introduceParameterObject....
- marshray 14y agoYou have a group of parameters that naturally go together. ...when you have a bunch of methods that call each other, all of which have a clump of parameters that need this refactoring. In this case you don't want to apply Introduce Parameter Object because it would lead to lots of new objects There are times when this transformation yields simpler code, there are times when it makes things more complex, and there are a lot of cases in between where it's a judgment call.
- genwin 14y agoThen I might set a variable and return that. The goal is to make the function readily understood.
- mseepgood 14y ago> I've been taught by some pretty experienced engineers that in terms of readability, multiple return statements are a bad idea They were wrong and probably not as experienced as they/you thought. Guard clauses make code simpler and more understandable.
- adamnemecek 14y agoGuard clauses and single return statements are not mutually exclusive.
- masklinn 14y agoThe whole idea of guard clauses in algol-derived languages (not functional ones) is to bail out immediately with an early return... http://martinfowler.com/refactoring/catalog/replaceNestedConditionalWithGuardClauses.html http://martinfowler.com/refactoring/catalog/replaceNestedCon...
- adamnemecek 14y agoI understand that but you can have a macro wrapping a goto statement to a predefined label which will do that for you (and potentially set some errors). It's debatable whether this really gives you anything but I kind of like this style since you can replace the whole if statement with a single line something like check_memory(pointer);. The goto's become particularly useful if you want to have some cleanup done at the end of the function even if something during the function fails.
- masklinn 14y agoNow your assuming the language has goto. Which definitely is not the case these days.
- adamnemecek 14y agoWell the discussion is about go and go does have gotos. http://golang.org/ref/spec#Goto_statements http://golang.org/ref/spec#Goto_statements
- jemfinch 14y agoYou were misled by engineers parroting the ideology they were taught in school. Else statements are far less readable than straight-line control flow with early returns.
- ebiester 14y agoI agree with the other commenters, but I'll say that I understand the original intent of the rule was to avoid confusing logic, such as: if (x): do(thing1) y := do(thing2) if (y): do(thing3) return 0 else: return -1 else: do(thing4) return 0 ___ As you can see, such logic could quickly become hard to test and reason about. Does a single return help all that much? Not in and of itself, but it does tend to make writing such code a bit more painful, leading to better designs. However, guard clauses are a superior design in general. I still avoid multiple returns in my main logic when side effects are involved, at least when I can.
- svachalek 14y agoLogically, a simple if-else return tends to follow three basic forms: if x return a return b if x return a else return b if x r = a else r = b return r Out of these I find the first is the most prone to maintenance errors. It's easy at a glance to see the final return, insert something in front of it, and miss that it needs to happen on another path. At least in the other two cases the indentation makes it clear that it's a conditional return path and you look for others. I don't have a problem with a "throw" instead of "return a" in any of the forms because that's expected to be an aborted path anyway. In the case of two returns, maybe it is, maybe it isn't. It's a small thing but when you read hundreds of thousands of lines of code, every little thing that makes it easier is worthwhile.
- marshray 14y agoI prefer to avoid multiple return statements and follow the single-return-at-the-end rule. However, I happily make exceptions for: a) Simple shortcut checks at the top of the function. These tend not to increase the complexity of the control flow and can really simplify it. void free(void * p) { if (!p) return; ... rest of function } b) Cases where it's just plain unnatural to do it any other way. This can occur with state machines and complex loops. When I do this, I make sure to put a comment way out on the right. void process_bytes(unsigned char * p) { ... for (;;) { ... switch (loop_state) { ... case specific_case: switch (input_symbol) { ... case end_symbol: return; //----- note inner return ... } break; ... } } } Before folks jump on me for having nested switch statements or "complex loops" in the first place, let me point out that when I write this type of code it's usually because I'm processing a data format defined by somebody else.
- gigq 14y agoThe mentality of using a single return statement at the end of a function comes from languages that require memory management. In these languages if you return early you would cause a leak by not releasing your resources at the bottom of the function before returning. http://programmers.stackexchange.com/a/118717 http://programmers.stackexchange.com/a/118717
- mzl 14y agoIn a question about this on programmers.se, a slightly different history of the "Single Entry, Single Return" mantra is presented: http://programmers.stackexchange.com/a/118793/4025 http://programmers.stackexchange.com/a/118793/4025 Essentially, it is argued that the practice that is warned about is to return to different places from the same function, not from different places within the function. On a separate note, my take is that multiple returns are necessary to write readable understandable code quite often. Guard statements (either handling normal simple boundary cases, or throwing exceptions) at the beginning simplify logic and gives a clean reading of the code.
- cmccabe 14y agoHaving a single return point is a pretty good idea in C. In other programming languages, probably not.