<p>Are there good reasons why it's a better practice to have only one return statement in a function? </p>

<p>Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?</p>

[{'answer_id': 36711, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 3, 'selected': False, 'text': '<p>I would say you should have as many as required, or any that make the code cleaner (such as <a href="http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html" rel="noreferrer">guard clauses</a>).</p>\n\n<p>I have personally never heard/seen any "best practices" say that you should have only one return statement.</p>\n\n<p>For the most part, I tend to exit a function as soon as possible based on a logic path (guard clauses are an excellent example of this).</p>\n'}, {'answer_id': 36713, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 3, 'selected': False, 'text': "<p>One good reason I can think of is for code maintenance: you have a single point of exit. If you want to change the format of the result,..., it's just much simpler to implement. Also, for debugging, you can just stick a breakpoint there :)</p>\n\n<p>Having said that, I once had to work in a library where the coding standards imposed 'one return statement per function', and I found it pretty tough. I write lots of numerical computations code, and there often are 'special cases', so the code ended up being quite hard to follow...</p>\n"}, {'answer_id': 36714, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 11, 'selected': True, 'text': '<p>I often have several statements at the start of a method to return for "easy" situations. For example, this:</p>\n\n<pre class="lang-java prettyprint-override"><code>public void DoStuff(Foo foo)\n{\n    if (foo != null)\n    {\n        ...\n    }\n}\n</code></pre>\n\n<p>... can be made more readable (IMHO) like this:</p>\n\n<pre class="lang-java prettyprint-override"><code>public void DoStuff(Foo foo)\n{\n    if (foo == null) return;\n\n    ...\n}\n</code></pre>\n\n<p>So yes, I think it\'s fine to have multiple "exit points" from a function/method.</p>\n'}, {'answer_id': 36724, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Structured_programming" rel="noreferrer">Structured programming</a> says you should only ever have one return statement per function. This is to limit the complexity. Many people such as Martin Fowler argue that it is simpler to write functions with multiple return statements. He presents this argument in the classic <a href="https://rads.stackoverflow.com/amzn/click/com/0201485672" rel="noreferrer" rel="nofollow noreferrer">refactoring</a> book he wrote. This works well if you follow his other advice and write small functions. I agree with this point of view and only strict structured programming purists adhere to single return statements per function.</p>\n'}, {'answer_id': 36725, 'author': 'Phil Bennett', 'author_id': 2995, 'author_profile': 'https://Stackoverflow.com/users/2995', 'pm_score': 3, 'selected': False, 'text': "<p>I've worked with terrible coding standards that forced a single exit path on you and the result is nearly always unstructured spaghetti if the function is anything but trivial -- you end up with lots of breaks and continues that just get in the way.</p>\n"}, {'answer_id': 36729, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 8, 'selected': False, 'text': '<p>I would say it would be incredibly unwise to decide arbitrarily against multiple exit points as I have found the technique to be useful in practice <em>over and over again</em>, in fact I have often <em>refactored existing code</em> to multiple exit points for clarity. We can compare the two approaches thus:-</p>\n\n<pre class="lang-cs prettyprint-override"><code>string fooBar(string s, int? i) {\n  string ret = "";\n  if(!string.IsNullOrEmpty(s) &amp;&amp; i != null) {\n    var res = someFunction(s, i);\n\n    bool passed = true;\n    foreach(var r in res) {\n      if(!r.Passed) {\n        passed = false;\n        break;\n      }\n    }\n\n    if(passed) {\n      // Rest of code...\n    }\n  }\n\n  return ret;\n}\n</code></pre>\n\n<p>Compare this to the code where multiple exit points <em>are</em> permitted:-</p>\n\n<pre class="lang-cs prettyprint-override"><code>string fooBar(string s, int? i) {\n  var ret = "";\n  if(string.IsNullOrEmpty(s) || i == null) return null;\n\n  var res = someFunction(s, i);\n\n  foreach(var r in res) {\n      if(!r.Passed) return null;\n  }\n\n  // Rest of code...\n\n  return ret;\n}\n</code></pre>\n\n<p>I think the latter is considerably clearer. As far as I can tell the criticism of multiple exit points is a rather archaic point of view these days.</p>\n'}, {'answer_id': 36731, 'author': 'Pete Kirkham', 'author_id': 1527, 'author_profile': 'https://Stackoverflow.com/users/1527', 'pm_score': 5, 'selected': False, 'text': "<p>I've seen it in coding standards for C++ that were a hang-over from C, as if you don't have RAII or other automatic memory management then you have to clean up for each return, which either means cut-and-paste of the clean-up or a goto (logically the same as 'finally' in managed languages), both of which are considered bad form. If your practices are to use smart pointers and collections in C++ or another automatic memory system, then there isn't a strong reason for it, and it become all about readability, and more of a judgement call. </p>\n"}, {'answer_id': 36732, 'author': 'blank', 'author_id': 1348, 'author_profile': 'https://Stackoverflow.com/users/1348', 'pm_score': 6, 'selected': False, 'text': '<p>As Kent Beck notes when discussing guard clauses in <a href="http://www.amazon.co.uk/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091/" rel="noreferrer">Implementation Patterns</a> making a routine have a single entry and exit point ...</p>\n\n<blockquote>\n  <p>"was to prevent the confusion possible\n  when jumping into and out of many\n  locations in the same routine. It made\n  good sense when applied to FORTRAN or\n  assembly language programs written\n  with lots of global data where even\n  understanding which statements were\n  executed was hard work ... with small methods and mostly local data, it is needlessly conservative."</p>\n</blockquote>\n\n<p>I find a function written with guard clauses much easier to follow than one long nested bunch of <code>if then else</code> statements.</p>\n'}, {'answer_id': 36752, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 4, 'selected': False, 'text': '<p>In general I try to have only a single exit point from a function. There are times, however, that doing so actually ends up creating a more complex function body than is necessary, in which case it\'s better to have multiple exit points. It really has to be a "judgement call" based on the resulting complexity, but the goal should be as few exit points as possible without sacrificing complexity and understandability.</p>\n'}, {'answer_id': 36839, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 8, 'selected': False, 'text': '<p>I currently am working on a codebase where two of the people working on it blindly subscribe to the "single point of exit" theory and I can tell you that from experience, it\'s a horrible horrible practice.  It makes code extremely difficult to maintain and I\'ll show you why.</p>\n\n<p>With the "single point of exit" theory, you inevitably wind up with code that looks like this:</p>\n\n<pre><code>function()\n{\n    HRESULT error = S_OK;\n\n    if(SUCCEEDED(Operation1()))\n    {\n        if(SUCCEEDED(Operation2()))\n        {\n            if(SUCCEEDED(Operation3()))\n            {\n                if(SUCCEEDED(Operation4()))\n                {\n                }\n                else\n                {\n                    error = OPERATION4FAILED;\n                }\n            }\n            else\n            {\n                error = OPERATION3FAILED;\n            }\n        }\n        else\n        {\n            error = OPERATION2FAILED;\n        }\n    }\n    else\n    {\n        error = OPERATION1FAILED;\n    }\n\n    return error;\n}\n</code></pre>\n\n<p>Not only does this make the code very hard to follow, but now say later on you need to go back and add an operation in between 1 and 2.  You have to indent just about the entire freaking function, and good luck making sure all of your if/else conditions and braces are matched up properly.</p>\n\n<p>This method makes code maintenance extremely difficult and error prone.</p>\n'}, {'answer_id': 36857, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 3, 'selected': False, 'text': "<p>Multiple exit points are fine for small enough functions -- that is, a function that can be viewed on one screen length on its entirety. If a lengthy function likewise includes multiple exit points, it's a sign that the function can be chopped up further.</p>\n\n<p>That said I avoid multiple-exit functions <em>unless absolutely necessary</em>. I have felt pain of bugs that are due to some stray return in some obscure line in more complex functions.</p>\n"}, {'answer_id': 36870, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 3, 'selected': False, 'text': '<p>There are good things to say about having a single exit-point, just as there are bad things to say about the inevitable <a href="http://c2.com/cgi/wiki?ArrowAntiPattern" rel="nofollow noreferrer">"arrow"</a> programming that results.</p>\n\n<p>If using multiple exit points during input validation or resource allocation, I try to put all the \'error-exits\' very visibly at the top of the function.</p>\n\n<p>Both the <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming" rel="nofollow noreferrer">Spartan Programming</a> article of the "SSDSLPedia" and <a href="http://c2.com/cgi/wiki?SingleFunctionExitPoint" rel="nofollow noreferrer">the single function exit point</a> article of the "Portland Pattern Repository\'s Wiki" have some insightful arguments around this. Also, of course, there is this post to consider.</p>\n\n<p>If you really want a single exit-point (in any non-exception-enabled language) for example in order to release resources in one single place, I find the careful application of goto to be good; see for example this rather contrived example (compressed to save screen real-estate):</p>\n\n<pre class="lang-c prettyprint-override"><code>int f(int y) {\n    int value = -1;\n    void *data = NULL;\n\n    if (y &lt; 0)\n        goto clean;\n\n    if ((data = malloc(123)) == NULL)\n        goto clean;\n\n    /* More code */\n\n    value = 1;\nclean:\n   free(data);\n   return value;\n}\n</code></pre>\n\n<p>Personally I, in general, dislike arrow programming more than I dislike multiple exit-points, although both are useful when applied correctly. The best, of course, is to structure your program to require neither. Breaking down your function into multiple chunks usually help :)</p>\n\n<p>Although when doing so, I find I end up with multiple exit points anyway as in this example, where some larger function has been broken down into several smaller functions:</p>\n\n<pre class="lang-c prettyprint-override"><code>int g(int y) {\n  value = 0;\n\n  if ((value = g0(y, value)) == -1)\n    return -1;\n\n  if ((value = g1(y, value)) == -1)\n    return -1;\n\n  return g2(y, value);\n}\n</code></pre>\n\n<p>Depending on the project or coding guidelines, most of the boiler-plate code could be replaced by macros. As a side note, breaking it down this way makes the functions g0, g1 ,g2 very easy to test individually.</p>\n\n<p>Obviously, in an OO and exception-enabled language, I wouldn\'t use if-statements like that (or at all, if I could get away with it with little enough effort), and the code would be much more plain. And non-arrowy. And most of the non-final returns would probably be exceptions.</p>\n\n<p>In short;</p>\n\n<ul>\n<li>Few returns are better than many returns</li>\n<li>More than one return is better than huge arrows, and <a href="http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html" rel="nofollow noreferrer">guard clauses</a> are generally ok.</li>\n<li>Exceptions could/should probably replace most \'guard clauses\' when possible.</li>\n</ul>\n'}, {'answer_id': 40697, 'author': 'John Channing', 'author_id': 3305, 'author_profile': 'https://Stackoverflow.com/users/3305', 'pm_score': 4, 'selected': False, 'text': '<p>Having a single exit point reduces <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">Cyclomatic Complexity</a> and therefore, <em>in theory</em>, reduces the probability that you will introduce bugs into your code when you change it.  Practice however, tends to suggest that a more pragmatic approach is needed.  I therefore tend to aim to have a single exit point, but allow my code to have several if that is more readable.</p>\n'}, {'answer_id': 42683, 'author': 'Eyal', 'author_id': 4454, 'author_profile': 'https://Stackoverflow.com/users/4454', 'pm_score': -1, 'selected': False, 'text': "<p>I'm usually in favor of multiple return statements.  They are easiest to read.</p>\n\n<p>There are situations where it isn't good.  Sometimes returning from a function can be very complicated.  I recall one case where all functions had to link into multiple different libraries.  One library expected return values to be error/status codes and others didn't.  Having a single return statement can save time there.</p>\n\n<p>I'm surprised that no one mentioned goto.  Goto is not the bane of programming that everyone would have you believe.  If you must have just a single return in each function, put it at the end and use gotos to jump to that return statement as needed.  Definitely avoid flags and arrow programming which are both ugly and run slowly.</p>\n"}, {'answer_id': 48630, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 6, 'selected': False, 'text': "<p>In a function that has no side-effects, there's no good reason to have more than a single return and you should write them in a functional style. In a method with side-effects, things are more sequential (time-indexed), so you write in an imperative style, using the return statement as a command to stop executing.</p>\n\n<p>In other words, when possible, favor this style</p>\n\n<pre><code>return a &gt; 0 ?\n  positively(a):\n  negatively(a);\n</code></pre>\n\n<p>over this</p>\n\n<pre><code>if (a &gt; 0)\n  return positively(a);\nelse\n  return negatively(a);\n</code></pre>\n\n<p>If you find yourself writing several layers of nested conditions, there's probably a way you can refactor that, using predicate list for example. If you find that your ifs and elses are far apart syntactically, you might want to break that down into smaller functions. A conditional block that spans more than a screenful of text is hard to read.</p>\n\n<p>There's no hard and fast rule that applies to every language. Something like having a single return statement won't make your code good. But good code will tend to allow you to write your functions that way.</p>\n"}, {'answer_id': 48645, 'author': 'hazzen', 'author_id': 5066, 'author_profile': 'https://Stackoverflow.com/users/5066', 'pm_score': 2, 'selected': False, 'text': '<p>The more return statements you have in a function, the higher complexity in that one method. If you find yourself wondering if you have too many return statements, you might want to ask yourself if you have too many lines of code in that function.</p>\n\n<p>But, not, there is nothing wrong with one/many return statements. In some languages, it is a better practice (C++) than in others (C).</p>\n'}, {'answer_id': 48666, 'author': 'rrichter', 'author_id': 5038, 'author_profile': 'https://Stackoverflow.com/users/5038', 'pm_score': 2, 'selected': False, 'text': '<p>You already implicitly have multiple implicit return statements, caused by error handling, so deal with it.</p>\n\n<p>As is typical with programming, though, there are examples both for and against the multiple return practice.  If it makes the code clearer, do it one way or the other.  Use of many control structures can help (the <strong>case</strong> statement, for example).  </p>\n'}, {'answer_id': 55957, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': 3, 'selected': False, 'text': '<p>Single exit point - all other things equal - makes code significantly more readable.\nBut there\'s a catch: popular construction </p>\n\n<pre><code>resulttype res;\nif if if...\nreturn res;\n</code></pre>\n\n<p>is a fake, "res=" is not much better than "return". It has single return statement, but multiple points where function actually ends.</p>\n\n<p>If you have function with multiple returns (or "res="s), it\'s often a good idea to break it into several smaller functions with single exit point.</p>\n'}, {'answer_id': 55966, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 3, 'selected': False, 'text': "<p>My usual policy is to have only one return statement at the end of a function unless the complexity of the code is greatly reduced by adding more. In fact, I'm rather a fan of Eiffel, which enforces the only one return rule by having no return statement (there's just a auto-created 'result' variable to put your result in).</p>\n\n<p>There certainly are cases where code can be made clearer with multiple returns than the obvious version without them would be. One could argue that more rework is needed if you have a function that is too complex to be understandable without multiple return statements, but sometimes it's good to be pragmatic about such things.</p>\n"}, {'answer_id': 56099, 'author': 'Marcin Gil', 'author_id': 5731, 'author_profile': 'https://Stackoverflow.com/users/5731', 'pm_score': 1, 'selected': False, 'text': "<p>I use multiple exit points for having error-case + handling + return value as close in proximity as possible.</p>\n\n<p>So having to test for conditions a, b, c that have to be true and you need to handle each of them differently:</p>\n\n<pre><code>if (a is false) {\n    handle this situation (eg. report, log, message, etc.)\n    return some-err-code\n}\nif (b is false) {\n    handle this situation\n    return other-err-code\n}\nif (c is false) {\n    handle this situation\n    return yet-another-err-code\n}\n\nperform any action assured that a, b and c are ok.\n</code></pre>\n\n<p>The a, b and c might be different things, like a is input parameter check, b is pointer check to newly allocated memory and c is check for a value in 'a' parameter.</p>\n"}, {'answer_id': 64155, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 3, 'selected': False, 'text': '<p>If you end up with more than a few returns there may be something wrong with your code. Otherwise I would agree that sometimes it is nice to be able to return from multiple places in a subroutine, especially when it make the code cleaner.</p>\n<h3>Perl 6: Bad Example</h3>\n<pre><code>sub Int_to_String( Int i ){\n  given( i ){\n    when 0 { return &quot;zero&quot; }\n    when 1 { return &quot;one&quot; }\n    when 2 { return &quot;two&quot; }\n    when 3 { return &quot;three&quot; }\n    when 4 { return &quot;four&quot; }\n    ...\n    default { return undef }\n  }\n}\n</code></pre>\n<p>would be better written like this</p>\n<h3>Perl 6: Good Example</h3>\n<pre><code>@Int_to_String = qw{\n  zero\n  one\n  two\n  three\n  four\n  ...\n}\nsub Int_to_String( Int i ){\n  return undef if i &lt; 0;\n  return undef unless i &lt; @Int_to_String.length;\n  return @Int_to_String[i]\n}\n</code></pre>\n<p><em><strong>Note this is was just a quick example</strong></em></p>\n'}, {'answer_id': 85911, 'author': 'Richard Corden', 'author_id': 11698, 'author_profile': 'https://Stackoverflow.com/users/11698', 'pm_score': 4, 'selected': False, 'text': '<p>My preference would be for single exit unless it really complicates things.  I have found that in some cases, multiple exist points can mask other more significant design problems:</p>\n\n<pre class="lang-java prettyprint-override"><code>public void DoStuff(Foo foo)\n{\n    if (foo == null) return;\n}\n</code></pre>\n\n<p>On seeing this code, I would immediately ask: </p>\n\n<ul>\n<li>Is \'foo\' ever null?</li>\n<li>If so, how many clients of \'DoStuff\' ever call the function with a null \'foo\'?</li>\n</ul>\n\n<p>Depending on the answers to these questions it might be that </p>\n\n<ol>\n<li>the check is pointless as it never is true (ie. it should be an assertion)</li>\n<li>the check is very rarely true and so it may be better to change those specific caller functions as they should probably take some other action anyway.</li>\n</ol>\n\n<p>In both of the above cases the code can probably be reworked with an assertion to ensure that \'foo\' is never null and the relevant callers changed.</p>\n\n<p>There are two other reasons (specific I think to C++ code) where multiple exists can actually have a <strong>negative</strong> affect.  They are code size, and compiler optimizations.</p>\n\n<p>A non-POD C++ object in scope at the exit of a function will have its destructor called.    Where there are several return statements, it may be the case that there are different objects in scope and so the list of destructors to call will be different.  The compiler therefore needs to generate code for each return statement:</p>\n\n<pre class="lang-java prettyprint-override"><code>void foo (int i, int j) {\n  A a;\n  if (i &gt; 0) {\n     B b;\n     return ;   // Call dtor for \'b\' followed by \'a\'\n  }\n  if (i == j) {\n     C c;\n     B b;\n     return ;   // Call dtor for \'b\', \'c\' and then \'a\'\n  }\n  return \'a\'    // Call dtor for \'a\'\n}\n</code></pre>\n\n<p>If code size is an issue - then this may be something worth avoiding.</p>\n\n<p>The other issue relates to "Named Return Value OptimiZation" (aka Copy Elision, ISO C++ \'03 12.8/15).  C++ allows an implementation to skip calling the copy constructor if it can:</p>\n\n<pre class="lang-java prettyprint-override"><code>A foo () {\n  A a1;\n  // do something\n  return a1;\n}\n\nvoid bar () {\n  A a2 ( foo() );\n}\n</code></pre>\n\n<p>Just taking the code as is, the object \'a1\' is constructed in \'foo\' and then its copy construct will be called to construct \'a2\'.  However, copy elision allows the compiler to construct \'a1\' in the same place on the stack as \'a2\'.  There is therefore no need to "copy" the object when the function returns.</p>\n\n<p>Multiple exit points complicates the work of the compiler in trying to detect this, and at least for a relatively recent version of VC++ the optimization did not take place where the function body had multiple returns.  See <a href="http://blogs.msdn.com/aymans/archive/2005/10/13/480699.aspx" rel="nofollow noreferrer">Named Return Value Optimization in Visual C++ 2005</a> for more details.</p>\n'}, {'answer_id': 89641, 'author': 'Paulus', 'author_id': 14209, 'author_profile': 'https://Stackoverflow.com/users/14209', 'pm_score': -1, 'selected': False, 'text': '<p><strong>Multiple exit is good if you manage it well</strong></p>\n\n<p>The first step is to specify the reasons of exit. Mine is usually something like this:<br>\n1. No need to execute the function<br>\n2. Error is found<br>\n3. Early completion<br>\n4. Normal completion<br>\nI suppose you can group "1. No need to execute the function" into "3. Early completion" (a very early completion if you will).</p>\n\n<p>The second step is to let the world outside the function know the reason of exit. The pseudo-code looks something like this:</p>\n\n<pre><code>function foo (input, output, exit_status)\n\n  exit_status == UNDEFINED\n  if (check_the_need_to_execute == false) then\n    exit_status = NO_NEED_TO_EXECUTE  // reason #1 \n    exit\n\n  useful_work\n\n  if (error_is_found == true) then\n    exit_status = ERROR               // reason #2\n    exit\n  if (need_to_go_further == false) then\n    exit_status = EARLY_COMPLETION    // reason #3\n    exit\n\n  more_work\n\n  if (error_is_found == true) then\n    exit_status = ERROR\n  else\n    exit_status = NORMAL_COMPLETION   // reason #4\n\nend function\n</code></pre>\n\n<p>Obviously, if it\'s beneficial to move a lump of work in the illustration above into a separate function, you should do so.</p>\n\n<p>If you want to, you can be more specific with the exit status, say, with several error codes and early completion codes to pinpoint the reason (or even the location) of exit.</p>\n\n<p>Even if you force this function into one that has only a single exit, I think you still need to specify exit status anyway. The caller needs to know whether it\'s OK to use the output, and it helps maintenance.</p>\n'}, {'answer_id': 124300, 'author': 'John Gardner', 'author_id': 13687, 'author_profile': 'https://Stackoverflow.com/users/13687', 'pm_score': 0, 'selected': False, 'text': "<p>As an alternative to the nested IFs, there's a way to use <code>do</code>/<code>while(false)</code> to break out anywhere:</p>\n\n<pre><code>    function()\n    {\n        HRESULT error = S_OK;\n\n        do\n        {\n            if(!SUCCEEDED(Operation1()))\n            {\n                error = OPERATION1FAILED;\n                break;\n            }\n\n            if(!SUCCEEDED(Operation2()))\n            {\n                error = OPERATION2FAILED;\n                break;\n            }\n\n            if(!SUCCEEDED(Operation3()))\n            {\n                error = OPERATION3FAILED;\n                break;\n            }\n            if(!SUCCEEDED(Operation4()))\n            {\n                error = OPERATION4FAILED;\n                break;\n            }\n        } while (false);\n\n        return error;\n    }\n</code></pre>\n\n<p>That gets you one exit point, lets you have other nesting of operations, but still not a real deep structure.  If you don't like the !SUCCEEDED you could always do FAILED whatever.  This kind of thing also lets you add other code between any two other checks without having to re-indent anything.</p>\n\n<p>If you were really crazy, that whole <code>if</code> block could be macroized too. :D</p>\n\n<pre><code>    #define BREAKIFFAILED(x,y) if (!SUCCEEDED((x))) { error = (Y); break; }\n\n    do\n    {\n        BREAKIFFAILED(Operation1(), OPERATION1FAILED)\n        BREAKIFFAILED(Operation2(), OPERATION2FAILED)\n        BREAKIFFAILED(Operation3(), OPERATION3FAILED)\n        BREAKIFFAILED(Operation4(), OPERATION4FAILED)\n    } while (false);\n</code></pre>\n"}, {'answer_id': 124590, 'author': 'Andrew Edgecombe', 'author_id': 11694, 'author_profile': 'https://Stackoverflow.com/users/11694', 'pm_score': 2, 'selected': False, 'text': '<p>This is probably an unusual perspective, but I think that anyone who believes that multiple return statements are to be favoured has never had to use a debugger on a microprocessor that supports only 4 hardware breakpoints. ;-)</p>\n\n<p>While the issues of "arrow code" are completely correct, one issue that seems to go away when using multiple return statements is in the situation where you are using a debugger. You have no convenient catch-all position to put a breakpoint to guarantee that you\'re going to see the exit and hence the return condition.</p>\n'}, {'answer_id': 139816, 'author': 'JosephStyons', 'author_id': 672, 'author_profile': 'https://Stackoverflow.com/users/672', 'pm_score': 2, 'selected': False, 'text': "<p>It doesn't make sense to always <em>require</em> a single return type.  I think it is more of a flag that something may need to be simplified.  Sometimes it's necessary to have multiple returns, but often you can keep things simpler by at least <em>trying</em> to have a single exit point.</p>\n"}, {'answer_id': 390756, 'author': 'Mike A', 'author_id': 48814, 'author_profile': 'https://Stackoverflow.com/users/48814', 'pm_score': -1, 'selected': False, 'text': '<h1>You should <em>never</em> use a return statement in a method.</h1>\n<p>I know I will be jumped on for this, but I am serious.</p>\n<p>Return statements are basically a hangover from the procedural programming days. They are a form of goto, along with break, continue, if, switch/case, while, for, yield and some other statements and the equivalents in most modern programming languages.</p>\n<p>Return statements effectively \'GOTO\' the point where the function was called, assigning a variable in that scope.</p>\n<p>Return statements are what I call a \'Convenient Nightmare\'. They seem to get things done quickly, but cause massive maintenance headaches down the line.</p>\n<h1>Return statements are diametrically opposed to Encapsulation</h1>\n<p>This is the most important and fundamental concept of object oriented programming. It is the raison d\'etre of OOP.</p>\n<p>Whenever you return anything from a method, you are basically \'leaking\' state information from the object. It doesn\'t matter if your state has changed or not, nor whether this information comes from other objects - it makes no difference to the caller. What this does is allow an object\'s behaviour to be outside of the object - breaking encapsulation. It allows the caller to start manipulating the object in ways that lead to fragile designs.</p>\n<h1>LoD is your friend</h1>\n<p>I recommend any developer to read about the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow noreferrer">Law of Demeter</a> (LoD) on c2.com or Wikipedia. LoD is a design philosophy that has been used at places that have real \'mission-critical\' software constraints in the literal sense, like the JPL. It has been shown to reduce the amount of bugs in code and improve flexibility.</p>\n<p>There has an excellent analogy based on walking a dog. When you walk a dog, you do not physically grab hold of its legs and move them such that the dog walks. You command the dog to walk and it takes care of it\'s own legs. A return statement in this analogy is equivalent to the dog letting you grab hold of its legs.</p>\n<h1>Only talk to your immediate friends:</h1>\n<ol>\n<li>arguments of the function you are in,</li>\n<li>your own attributes,</li>\n<li>any objects you created within the function</li>\n</ol>\n<p>You will notice that none of these require a return statement. You might think the constructor is a return, and you are on to something. Actually the return is from the memory allocator. The constructor just sets what is in the memory. This is OK so long as the encapsulation of that new object is OK, because, as you made it, you have full control over it - no-one else can break it.</p>\n<p>Accessing attributes of other objects is right out. Getters are out (but you knew they were bad already, right?). Setters are OK, but it is better to use constructors. Inheritance is bad - when you inherit from another class, any changes in that class can and probably will break you. Type sniffing is bad (Yes - LoD implies that Java/C++ style type based dispatch is incorrect - asking about type, even implicitly, <em>is</em> breaking encapsulation. Type is an implicit attribute of an object. Interfaces are The Right Thing).</p>\n<p>So why is this all a problem? Well, unless your universe is very different from mine, you spend a lot of time debugging code. You aren\'t writing code that you plan never to reuse. Your software requirements are changing, and that causes internal API/interface changes. Every time you have used a return statement you have introduced a very tricky dependency - methods returning anything are required to know about how whatever they return is going to be used - that is each and every case! As soon as the interface changes, on one end or the other, everything can break, and you are faced with a lengthy and tedious bug hunt.</p>\n<p>They really are an malignant cancer in your code, because once you start using them, they promote further use elsewhere (which is why you can often find returning method-chains amongst object systems).</p>\n<p>So what is the alternative?</p>\n<h1><em>Tell</em>, don\'t ask.</h1>\n<p>With OOP - the goal is to tell other objects what to do, and let them take care of it. So you have to forget the procedural ways of doing things. It\'s easy really - just never write return statements. There are much better ways of doing the same things:</p>\n<h1>There is nothing wrong with the return <em>concept</em>, but return <em>statements</em> are deeply flawed.</h1>\n<p>If you really need an answer back - use a call back. Pass in a data structure to be filled in, even. That way you keep the interfaces clean and open to change, and your whole system is less fragile and more adaptable. It does not slow your system down, in fact it can speed it up, in the same way as tail call optimisation does - except in this case, there is no tail call so you don\'t even have to waste time manipulating the stack with return values.</p>\n<p>If you follow these arguments, you will find there really is <em>never</em> a need for a return statement.</p>\n<p>If you follow these practices, I guarantee that pretty soon you will find that you are spending a lot less time hunting bugs, are adapting to requirement changes much more quickly, and having less problems understanding your own code.</p>\n'}, {'answer_id': 391077, 'author': 'Daniel Earwicker', 'author_id': 27423, 'author_profile': 'https://Stackoverflow.com/users/27423', 'pm_score': 1, 'selected': False, 'text': "<p>In the interests of <em>good standards</em> and <em>industry best practises</em>, we must establish the correct number of return statements to appear in all functions. Obviously there is consensus against having one return statement. So I propose we set it at two.</p>\n\n<p>I would appreciate it if everyone would look through their code right now, locate any functions with only one exit point, and add another one. It doesn't matter where.</p>\n\n<p>The result of this change will undoubtedly be fewer bugs, greater readability and unimaginable wealth falling from the sky onto our heads.</p>\n"}, {'answer_id': 394108, 'author': 'martinus', 'author_id': 48181, 'author_profile': 'https://Stackoverflow.com/users/48181', 'pm_score': 2, 'selected': False, 'text': '<p>The only important question is "How is the code simpler, better readable, easier to understand?" If it is simpler with multiple returns, then use them.</p>\n'}, {'answer_id': 399747, 'author': 'starblue', 'author_id': 49246, 'author_profile': 'https://Stackoverflow.com/users/49246', 'pm_score': 1, 'selected': False, 'text': '<p>I prefer a single return statement. One reason which has not yet been pointed out is that some refactoring tools work better for single points of exit, e.g. Eclipse JDT extract/inline method.</p>\n'}, {'answer_id': 666041, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 5, 'selected': False, 'text': '<p>I lean to the idea that return statements in the <em>middle</em> of the function are bad. You can use returns to build a few guard clauses at the top of the function, and of course tell the compiler what to return at the end of the function without issue, but returns in the <em>middle</em> of the function can be easy to miss and can make the function harder to interpret.</p>\n'}, {'answer_id': 666273, 'author': 'TMN', 'author_id': 69471, 'author_profile': 'https://Stackoverflow.com/users/69471', 'pm_score': 2, 'selected': False, 'text': '<p>Well, maybe I\'m one of the few people here old enough to remember one of the big reasons why "only one return statement" was pushed so hard.  It\'s so the compiler can emit more efficient code.  For each function call, the compiler typically pushes some registers on the stack to preserve their values.  This way, the function can use those registers for temporary storage.  When the function returns, those saved registers have to be popped off the stack and back into the registers.  That\'s one POP (or MOV -(SP),Rn) instruction per register.  If you have a bunch of return statements, then either each one has to pop all the registers (which makes the compiled code bigger) or the compiler has to keep track of which registers might have been modified and only pop those (decreasing code size, but increasing compilation time).</p>\n\n<p>One reason why it still makes sense today to try to stick with one return statement is ease of automated refactoring.  If your IDE supports method-extraction refactoring (selecting a range of lines and turning them into a method), it\'s very difficult to do this if the lines you want to extract have a return statement in them, especially if you\'re returning a value.</p>\n'}, {'answer_id': 733858, 'author': 'Chris S', 'author_id': 21574, 'author_profile': 'https://Stackoverflow.com/users/21574', 'pm_score': 8, 'selected': False, 'text': '<p>Nobody has mentioned or quoted <a href="http://www.cc2e.com/" rel="noreferrer">Code Complete</a> so I\'ll do it.</p>\n<h2>17.1 return</h2>\n<p><strong>Minimize the number of returns in each routine</strong>. It\'s harder to understand a routine if, reading it at the bottom, you\'re unaware of the possibility that it returned somewhere above.</p>\n<p><strong>Use a <em>return</em> when it enhances readability</strong>. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn\'t require any cleanup, not returning immediately means that you have to write more code.</p>\n'}, {'answer_id': 790043, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>There are times when it is necessary for performance reasons (I don\'t want to fetch a different cache line kind of the same need as a continue; sometimes).</p>\n\n<p>If you allocate resources (memory, file descriptors, locks, etc.) without using RAII then muliple returns can be error prone and are certainly duplicative as the releases need to be done manually multiple times and you must keep careful track.</p>\n\n<p>In the example:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>function()\n{\n    HRESULT error = S_OK;\n\n    if(SUCCEEDED(Operation1()))\n    {\n        if(SUCCEEDED(Operation2()))\n        {\n            if(SUCCEEDED(Operation3()))\n            {\n                if(SUCCEEDED(Operation4()))\n                {\n                }\n                else\n                {\n                    error = OPERATION4FAILED;\n                }\n            }\n            else\n            {\n                error = OPERATION3FAILED;\n            }\n        }\n        else\n        {\n            error = OPERATION2FAILED;\n        }\n    }\n    else\n    {\n        error = OPERATION1FAILED;\n    }\n\n    return error;\n}\n</code></pre>\n\n<p>I would have written it as:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>function() {\n    HRESULT error = OPERATION1FAILED;//assume failure\n    if(SUCCEEDED(Operation1())) {\n\n        error = OPERATION2FAILED;//assume failure\n        if(SUCCEEDED(Operation3())) {\n\n            error = OPERATION3FAILED;//assume failure\n            if(SUCCEEDED(Operation3())) {\n\n                error = OPERATION4FAILED; //assume failure\n                if(SUCCEEDED(Operation4())) {\n\n                    error = S_OK;\n                }\n            }\n        }\n    }\n    return error;\n}\n</code></pre>\n\n<p>Which certainly seems better.</p>\n\n<p>This tends to be especially helpful in the manual resource release case as where and which releases are necessary is pretty straightforward. As in the following example:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>function() {\n    HRESULT error = OPERATION1FAILED;//assume failure\n    if(SUCCEEDED(Operation1())) {\n\n        //allocate resource for op2;\n        char* const p2 = new char[1024];\n        error = OPERATION2FAILED;//assume failure\n        if(SUCCEEDED(Operation2(p2))) {\n\n            //allocate resource for op3;\n            char* const p3 = new char[1024];\n            error = OPERATION3FAILED;//assume failure\n            if(SUCCEEDED(Operation3(p3))) {\n\n                error = OPERATION4FAILED; //assume failure\n                if(SUCCEEDED(Operation4(p2,p3))) {\n\n                    error = S_OK;\n                }\n            }\n            //free resource for op3;\n            delete [] p3;\n        }\n        //free resource for op2;\n        delete [] p2;\n    }\n    return error;\n}\n</code></pre>\n\n<p>If you write this code without RAII (forgetting the issue of exceptions!) with multiple exits then the deletes have to be written multiple times. If you write it with <code>}else{</code> then\nit gets a little ugly.</p>\n\n<p>But RAII makes the multiple exit resource issue moot.</p>\n'}, {'answer_id': 792392, 'author': 'Alphaneo', 'author_id': 70702, 'author_profile': 'https://Stackoverflow.com/users/70702', 'pm_score': 3, 'selected': False, 'text': '<p>I vote for Single return at the end as a guideline. This helps a <strong>common code clean-up handling</strong> ... For example, take a look at the following code ...</p>\n\n<pre class="lang-c prettyprint-override"><code>void ProcessMyFile (char *szFileName)\n{\n   FILE *fp = NULL;\n   char *pbyBuffer = NULL:\n\n   do {\n\n      fp = fopen (szFileName, "r");\n\n      if (NULL == fp) {\n\n         break;\n      }\n\n      pbyBuffer = malloc (__SOME__SIZE___);\n\n      if (NULL == pbyBuffer) {\n\n         break;\n      }\n\n      /*** Do some processing with file ***/\n\n   } while (0);\n\n   if (pbyBuffer) {\n\n      free (pbyBuffer);\n   }\n\n   if (fp) {\n\n      fclose (fp);\n   }\n}\n</code></pre>\n'}, {'answer_id': 866092, 'author': 'Adrian McCarthy', 'author_id': 1386054, 'author_profile': 'https://Stackoverflow.com/users/1386054', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>Are there good reasons why it\'s a better practice to have only one return statement in a function?</p>\n</blockquote>\n\n<p><strong>Yes</strong>, there are:</p>\n\n<ul>\n<li>The single exit point gives an excellent place to assert your post-conditions.</li>\n<li>Being able to put a debugger breakpoint on the one return at the end of the function is often useful.</li>\n<li>Fewer returns means less complexity.  Linear code is generally simpler to understand.</li>\n<li>If trying to simplify a function to a single return causes complexity, then that\'s incentive to refactor to smaller, more general, easier-to-understand functions.</li>\n<li>If you\'re in a language without destructors or if you don\'t use RAII, then a single return reduces the number of places you have to clean up.</li>\n<li>Some languages require a single exit point (e.g., Pascal and Eiffel).</li>\n</ul>\n\n<p>The question is often posed as a false dichotomy between multiple returns or deeply nested if statements.  There\'s almost always a third solution which is very linear (no deep nesting) with only a single exit point.</p>\n\n<p><strong>Update</strong>: Apparently <a href="https://stackoverflow.com/questions/17177276/c-c-conditional-return-statements/17177315#17177315">MISRA guidelines promote single exit</a>, too.</p>\n\n<p>To be clear, I\'m not saying it\'s <em>always</em> wrong to have multiple returns.  But given otherwise equivalent solutions, there are lots of good reasons to prefer the one with a single return.</p>\n'}, {'answer_id': 1276951, 'author': 'Jrgns', 'author_id': 6681, 'author_profile': 'https://Stackoverflow.com/users/6681', 'pm_score': 4, 'selected': False, 'text': '<p>I force myself to use only one <code>return</code> statement, as it will in a sense generate code smell. Let me explain:</p>\n\n<pre class="lang-php prettyprint-override"><code>function isCorrect($param1, $param2, $param3) {\n    $toret = false;\n    if ($param1 != $param2) {\n        if ($param1 == ($param3 * 2)) {\n            if ($param2 == ($param3 / 3)) {\n                $toret = true;\n            } else {\n                $error = \'Error 3\';\n            }\n        } else {\n            $error = \'Error 2\';\n        }\n    } else {\n        $error = \'Error 1\';\n    }\n    return $toret;\n}\n</code></pre>\n\n<p><em>(The conditions are arbritary...)</em></p>\n\n<p>The more conditions, the larger the function gets, the more difficult it is to read. So if you\'re attuned to the code smell, you\'ll realise it, and want to refactor the code. Two possible solutions are:</p>\n\n<ul>\n<li>Multiple returns</li>\n<li>Refactoring into separate functions</li>\n</ul>\n\n<p><strong>Multiple Returns</strong></p>\n\n<pre class="lang-php prettyprint-override"><code>function isCorrect($param1, $param2, $param3) {\n    if ($param1 == $param2)       { $error = \'Error 1\'; return false; }\n    if ($param1 != ($param3 * 2)) { $error = \'Error 2\'; return false; }\n    if ($param2 != ($param3 / 3)) { $error = \'Error 3\'; return false; }\n    return true;\n}\n</code></pre>\n\n<p><strong>Separate Functions</strong></p>\n\n<pre class="lang-php prettyprint-override"><code>function isEqual($param1, $param2) {\n    return $param1 == $param2;\n}\n\nfunction isDouble($param1, $param2) {\n    return $param1 == ($param2 * 2);\n}\n\nfunction isThird($param1, $param2) {\n    return $param1 == ($param2 / 3);\n}\n\nfunction isCorrect($param1, $param2, $param3) {\n    return !isEqual($param1, $param2)\n        &amp;&amp; isDouble($param1, $param3)\n        &amp;&amp; isThird($param2, $param3);\n}\n</code></pre>\n\n<p>Granted, it is longer and a bit messy, but in the process of refactoring the function this way, we\'ve</p>\n\n<ul>\n<li>created a number of reusable functions,</li>\n<li>made the function more human readable, and</li>\n<li>the focus of the functions is on why the values are correct.</li>\n</ul>\n'}, {'answer_id': 2204081, 'author': 'Dinah', 'author_id': 356, 'author_profile': 'https://Stackoverflow.com/users/356', 'pm_score': 2, 'selected': False, 'text': '<p>Having multiple exit points is essentially the same thing as using a <code>GOTO</code>. Whether or not that\'s a bad thing depends on how you feel about raptors.</p>\n\n<p><img src="https://imgs.xkcd.com/comics/goto.png" /></p>\n'}, {'answer_id': 2236273, 'author': 'Serhiy', 'author_id': 246719, 'author_profile': 'https://Stackoverflow.com/users/246719', 'pm_score': 0, 'selected': False, 'text': '<p>I think in different situations different method is better. For example, if you should process the return value before return, you should have one point of exit. But in other situations, it is more comfortable to use several returns.</p>\n\n<p>One note. If you should process the return value before return in several situations, but not in all, the best solutions (IMHO) to define a method like ProcessVal and call it before return:</p>\n\n<pre><code>var retVal = new RetVal();\n\nif(!someCondition)\n    return ProcessVal(retVal);\n\nif(!anotherCondition)\n   return retVal;\n</code></pre>\n'}, {'answer_id': 2793043, 'author': 'Bubba88', 'author_id': 185430, 'author_profile': 'https://Stackoverflow.com/users/185430', 'pm_score': 2, 'selected': False, 'text': "<p>If it's okay to write down just an opinion, that's mine:</p>\n\n<p>I totally and absolutely disagree with the `Single return statement theory' and find it mostly speculative and even destructive regarding the code readability, logic and descriptive aspects.</p>\n\n<p>That habit of having one-single-return is even poor for bare procedural programming not to mention more high-level abstractions (functional, combinatory etc.). And furthermore, I wish all the code written in that style to go through some special rewriting parser to make it have <em>multiple</em> return statements!</p>\n\n<p>A function (if it's really a function/query according to `Query-Command separation' note - see Eiffel programming lang. for example) just MUST define as many return points as the control flow scenarios it has. It is much more clear and mathematically consistent; and it is the way to write <em>functions</em> (i.e. Queries)</p>\n\n<p>But I would not be so militant for the mutation messages that your agent does receive - the procedure calls.</p>\n"}, {'answer_id': 2863438, 'author': 'Zorf', 'author_id': 2281094, 'author_profile': 'https://Stackoverflow.com/users/2281094', 'pm_score': 0, 'selected': False, 'text': "<p>I'm probably going to be hated for this, but ideally there should be <em>no</em> return statement at all I think, a function should just return its last expression, and should in the completely ideal case contain only one.</p>\n\n<p>So not</p>\n\n<pre><code>function name(arg) {\n    if (arg.failure?)\n        return;\n\n    //code for non failure\n}\n</code></pre>\n\n<p>But rather</p>\n\n<pre><code>function name(arg) {\n    if (arg.failure?)\n        voidConstant\n    else {\n        //code for non failure\n\n\n}\n</code></pre>\n\n<p>If-statements that aren't expressions and return statements are a very dubious practise to me.</p>\n"}, {'answer_id': 3128187, 'author': 'Anthony', 'author_id': 5599, 'author_profile': 'https://Stackoverflow.com/users/5599', 'pm_score': 3, 'selected': False, 'text': '<p>I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren\'t coding in C.</p>\n\n<p><strong>There is no law requiring only one exit point for a method in all programming languages</strong>. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research. </p>\n\n<p>More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and <code>try..finally</code> blocks (and <code>using</code> blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation. </p>\n\n<p>There are cases where a single return is more readable, and cases where it isn\'t. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.</p>\n\n<p>Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.</p>\n\n<p>I have talked about <a href="http://www.anthonysteele.co.uk/the-single-exit-point-law" rel="noreferrer">this at greater length on my blog</a>.</p>\n'}, {'answer_id': 3249664, 'author': 'Ben Lings', 'author_id': 41012, 'author_profile': 'https://Stackoverflow.com/users/41012', 'pm_score': 4, 'selected': False, 'text': '<p>No, because <a href="http://en.wikipedia.org/wiki/Structured_programming" rel="noreferrer">we don\'t live in the 1970s any more</a>.  If your function is long enough that multiple returns are a problem, it\'s too long.</p>\n\n<p>(Quite apart from the fact that any multi-line function in a language with exceptions will have multiple exit points anyway.)</p>\n'}, {'answer_id': 3252702, 'author': 'Blessed Geek', 'author_id': 140803, 'author_profile': 'https://Stackoverflow.com/users/140803', 'pm_score': 3, 'selected': False, 'text': '<p>You know the adage - <strong>beauty is in the eyes of the beholder</strong>.</p>\n\n<p>Some people swear by <a href="http://en.wikipedia.org/wiki/NetBeans" rel="nofollow noreferrer">NetBeans</a> and some by <a href="http://en.wikipedia.org/wiki/IntelliJ_IDEA" rel="nofollow noreferrer">IntelliJ IDEA</a>, some by <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">Python</a> and some by <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow noreferrer">PHP</a>.</p>\n\n<p>In some shops you could lose your job if you insist on doing this:</p>\n\n<pre class="lang-java prettyprint-override"><code>public void hello()\n{\n   if (....)\n   {\n      ....\n   }\n}\n</code></pre>\n\n<p>The question is all about visibility and maintainability.</p>\n\n<p>I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.</p>\n\n<p>Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.</p>\n\n<p>I remember 20 years ago, a colleague of mine was fired for employing what today would be called <a href="http://en.wikipedia.org/wiki/Agile_software_development" rel="nofollow noreferrer">agile development</a> strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can\'t incrementally release features to users! You must stick with the <a href="http://en.wikipedia.org/wiki/Waterfall_model" rel="nofollow noreferrer">waterfall</a>." His response to the manager was that incremental development would be more precise to customer\'s needs. He believed in developing for the customers needs, but the manager believed in coding to "customer\'s requirement".</p>\n\n<p>We are frequently guilty for breaking data normalization, <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="nofollow noreferrer">MVP</a> and <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow noreferrer">MVC</a> boundaries. We inline instead of constructing a function. We take shortcuts.</p>\n\n<p>Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules</p>\n\n<blockquote>\n  <p>quality = precision, maintainability\n  and profitability.</p>\n</blockquote>\n\n<p>All other rules fade into the background. And of course this rule never fades:</p>\n\n<blockquote>\n  <p>Laziness is the virtue of a good\n  programmer.</p>\n</blockquote>\n'}, {'answer_id': 3320782, 'author': 'Mark', 'author_id': 400378, 'author_profile': 'https://Stackoverflow.com/users/400378', 'pm_score': 5, 'selected': False, 'text': '<p>Having a single exit point does provide an advantage in debugging, because it allows you to set a single breakpoint at the end of a function to see what value is actually going to be returned.</p>\n'}, {'answer_id': 4317061, 'author': 'BJS', 'author_id': 525534, 'author_profile': 'https://Stackoverflow.com/users/525534', 'pm_score': 1, 'selected': False, 'text': '<p>I always avoid multiple return statements. Even in small functions. Small functions can become larger, and tracking the multiple return paths makes it harder (to my small mind) to keep track of what is going on. A single return also makes debugging easier. I\'ve seen people post that the only alternative to multiple return statements is a messy arrow of nested IF statements 10 levels deep. While I certain agree that such coding does occur, it isn\'t the only option. I wouldn\'t make the choice between a multiple return statements and a nest of IFs, I\'d refactor it so you\'d eliminate both. And that is how I code. The following code eliminates both issues and, in my mind, is very easy to read:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>public string GetResult()\n{\n    string rv = null;\n    bool okay = false;\n\n    okay = PerformTest(1);\n\n    if (okay)\n    {\n        okay = PerformTest(2);\n    }\n\n    if (okay)\n    {\n        okay = PerformTest(3);\n    }\n\n    if (okay)\n    {\n        okay = PerformTest(4);\n    };\n\n    if (okay)\n    {\n        okay = PerformTest(5);\n    }\n\n    if (okay)\n    {\n        rv = "All Tests Passed";\n    }\n\n    return rv;\n}\n</code></pre>\n'}, {'answer_id': 5034398, 'author': 'David Clarke', 'author_id': 132599, 'author_profile': 'https://Stackoverflow.com/users/132599', 'pm_score': 3, 'selected': False, 'text': '<p>I lean towards using guard clauses to return early and otherwise exit at the end of a method. The single entry and exit rule has historical significance and was particularly helpful when dealing with legacy code that ran to 10 A4 pages for a single C++ method with multiple returns (and many defects). More recently, accepted good practice is to keep methods small which makes multiple exits less of an impedance to understanding. In the following Kronoz example copied from above, the question is what occurs in <em>//Rest of code...</em>?:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>void string fooBar(string s, int? i) {\n\n  if(string.IsNullOrEmpty(s) || i == null) return null;\n\n  var res = someFunction(s, i);\n\n  foreach(var r in res) {\n      if(!r.Passed) return null;\n  }\n\n  // Rest of code...\n\n  return ret;\n}\n</code></pre>\n\n<p>I realise the example is somewhat contrived but I would be tempted to refactor the <em>foreach</em> loop into a LINQ statement that could then be considered a guard clause. Again, in a contrived example the intent of the code isn\'t apparent and <em>someFunction()</em> may have some other side effect or the result may be used in the <em>// Rest of code...</em>.</p>\n\n<pre class="lang-cpp prettyprint-override"><code>if (string.IsNullOrEmpty(s) || i == null) return null;\nif (someFunction(s, i).Any(r =&gt; !r.Passed)) return null;\n</code></pre>\n\n<p>Giving the following refactored function:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>void string fooBar(string s, int? i) {\n\n  if (string.IsNullOrEmpty(s) || i == null) return null;\n  if (someFunction(s, i).Any(r =&gt; !r.Passed)) return null;\n\n  // Rest of code...\n\n  return ret;\n}\n</code></pre>\n'}, {'answer_id': 21793601, 'author': 'TaylorMac', 'author_id': 720785, 'author_profile': 'https://Stackoverflow.com/users/720785', 'pm_score': 0, 'selected': False, 'text': "<p>One might argue... if you have multiple conditions that must be satisfied <strong>before</strong> the tasks of the function are to be performed, then don't invoke the function until those conditions are met:</p>\n\n<p>Instead of:</p>\n\n<pre><code>function doStuff(foo) {\n    if (foo != null) return;\n}\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>function doStuff(foo) {\n    if (foo !== null) {\n        ...\n    }\n}\n</code></pre>\n\n<p>Don't invoke <code>doStuff</code> until <strong>foo != null</strong></p>\n\n<pre><code>if(foo != null) doStuff(foo);\n</code></pre>\n\n<p>Which, requires that every call site ensures that the <strong>conditions for the invocation</strong> are satisfied before the call. If there are multiple call sites, this logic is <strong>perhaps</strong> best placed in a separate function, in a method of the to-be-invoked function (assuming they are first-class citizens), or in a proxy.</p>\n\n<p>On the topic of whether or not the function is <strong>mathematically provable</strong>, consider the logic over the syntax. If a function has multiple return points, this doesn't mean (by default) that it is not mathematically provable.</p>\n"}, {'answer_id': 25201917, 'author': 'Tom Tanner', 'author_id': 1182921, 'author_profile': 'https://Stackoverflow.com/users/1182921', 'pm_score': 0, 'selected': False, 'text': "<p>This is mainly a hang over from Fortran, where it was possible to pass multiple statement labels to a function so it could return to any one of them.</p>\n\n<p>So this sort of code was perfectly valid</p>\n\n<pre><code>       CALL SOMESUB(ARG1, 101, 102, 103)\nC Some code\n 101   CONTINUE\nC Some more code\n 102   CONTINUE\nC Yet more code\n 103   CONTINUE\nC You get the general idea\n</code></pre>\n\n<p>But the function being called made the decision as to where your code path went. Efficient? Probably. Maintainable? No. </p>\n\n<p>That is where that rule comes from (incidentally along with no multiple entry points to a function, which is possible in fortran and assembler, but not in C).</p>\n\n<p>However, the wording of that looks like it can be applied to other languages (the one about multiple entry points can't be applied to other languages, so it's not really a program). So the rule got carried over, even though it refers to a completely different problem, and isn't applicable.</p>\n\n<p>For more structured languages, that rule needs to be dropped or at least thought through more. Certainly a function spattered with returns is difficult to understand, but returning at the beginning isn't an issue. And in some C++ compilers a single return point may generate better code if you're returning a value from only one place.</p>\n\n<p>But the original rule is misunderstood, misapplied. and no longer relevant.</p>\n"}, {'answer_id': 29472829, 'author': 'DarioBB', 'author_id': 4195191, 'author_profile': 'https://Stackoverflow.com/users/4195191', 'pm_score': 0, 'selected': False, 'text': '<p>You can do this for achieving only one return statement - declare it at start and output it at the end - problem solved:</p>\n\n<pre><code>$content = "";\n$return = false;\n\nif($content != "")\n{\n  $return = true;\n}\nelse \n{\n  $return = false;\n}\n\nreturn $return;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381/']