C/C++ [C++] Never have more than 1 return statement?

  • Thread starter Thread starter Jamin2112
  • Start date Start date
Click For Summary
The discussion centers on the debate over whether a function in C++ should have only one return statement. Some argue that having multiple return points can enhance readability and simplify code, especially in cases involving preconditions or error handling. Others advocate for a single exit point to improve debugging and maintainability, citing traditional coding standards and practices. The conversation highlights the tension between modern coding practices and older rules, with some participants suggesting that the single return point rule is outdated. Ultimately, the effectiveness of return statements depends on the context and complexity of the function being written.
Jamin2112
Messages
973
Reaction score
12
I know someone at Google who says you should never have more than 1 return statement in a function. That seems ridiculous to me.

Let's take a simple example. Suppose we need a function that finds the maximum value of any C++ array.

I can do

Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    if (n == 0)
    {
        return false;
    }
    else
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
        return true;
    }
}

or, equivalently,

Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    bool retval;
    if (n == 0)
    {
        retval = true;
    }
    else
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
        retval = false;
    }
   return retval;
}

Apparently, the first is considered bad because it has two return statements? The second seems very n00b-esque to me. (I know there's an even better way to do the whole function.)
 
Technology news on Phys.org
No, the first one is completely OK. I have no problem with it.
 
This advice was popularized in "Code Complete" which suggested you minimize returning early except when it would enhance readability.

I find the biggest benefit of the "one exit point" that you only need to set one breakpoint when debugging.

Though if you are keeping your functions small and uncomplicated this probably won't be much of an issue anyway.
 
Personally, I would be more worried about the value not returned in "highest" than about the number of return points :smile:
 
DavidSnider said:
This advice was popularized in "Code Complete" which suggested you minimize returning early except when it would enhance readability.
The "single point of entry / single point of exit" rule goes back much further than Code Complete. This rule is very old. The first part of the rule gives a clue as to how old this rule is. The facility to define alternate entry points to a function doesn't exist in C or C++, or in most other languages for that matter.

It's an old rule based on archaic concepts. It deserves to die.
I find the biggest benefit of the "one exit point" that you only need to set one breakpoint when debugging.
This benefit goes away with debuggers such as gdb that let you set a break point on the function's closing bracket.

Another supposed advantage of a single exit point is cleanup. Suppose a function creates and connects to a socket, opens a C-style stream, allocates an array via new, copies data from the socket to the stream, and then cleans things up. There are lots of things that can go wrong here. There's no point in continuing if the socket won't open properly, and then there's no stream to close, no array to delete. There are multiple ways in which the socket connection can fail, and the socket can fail while reading from it. The cleanup can be *ugly*. In fact, some advocate using goto to branch into the right part of the cleanup section.

There is a way around this cleanup problem in C++: Use RAII. Do this consistently and once again the impetus driving a single exit point vanishes.I'm a fan of "early exit". Suppose you've done a good job defining your functions in terms of preconditions, invariants, and postconditions. What to do about those preconditions? Suppose you are reading a complex function and the first thing you see are a handful of statements of the form
Code:
// Handle preconditions.

if (! precondition_1) {
   issue_error_message("Precondition 1 failed");
   return;
}

if (! precondition_2) {
   issue_error_message("Precondition 2 failed");
   return;
}
You know exactly what these checks are doing: They're ensuring the preconditions are met. That's the principle of least astonishment at work. The alternative of a single exit point can be more astonishing. You have to scroll all the way down to see that these preconditions just exit. Even worse, you may have to diagram some rather convoluted logic introduced just to comply with the "single point of entry / single point of exit" rule.
Though if you are keeping your functions small and uncomplicated this probably won't be much of an issue anyway.
Yep. The arguments I've seen for single point of entry / single point of exit are usually straw men. For example,
Code:
// 100s of lines of code elided
if (some_test) {
   return ERROR_CODE_1;
}
// 100s of lines of code elided
for (i = 0; i < first_limit; i++) {
   // 100s of lines of code elided
   if (some_other_test) {
      return ERROR_CODE_2;
   }
   // 100s of lines of code elided
   for (j = 0; j < second_limit; j++) {
      // 100s of lines of code elided
      if (yet_another_test) {
         return ERROR_CODE_3;
      }
      // 100s of lines of code elided
   }
   // 100s of lines of code elided
}
// 100s of lines of code elided
return SUCCESS;
That this code has four exit points interspersed randomly throughout several hundred lines of code is only the tip of the iceberg of the problems associated with this block of code.
 
The rationale behind it, is that if someone who is unfamiliar with the code wants to do something at the end of the function for all cases, then they can miss a return point and introduce a bug.

People who analyse this sort of stuff can estimate how often mistakes like this happen and their cost to a project. Future languages may even make it impossible.

I do it some cases, but then I'm mindful of how someone might modify my code and what I want the compiler to do with it.
 
Last edited:
craigi said:
The rationale behind it, is that if someone who is unfamiliar with the code wants to do something at the end of the function for all cases, then they can miss a return point and introduce a bug.

How did they know they wanted to do something at the end for all cases, unless they traced all the possible ways they could get to the one return point?

Thinking or assuming they wanted to do something in all cases (e.g. by believing or misunderstanding the documentation, but not actually reading the code) might also be a bug!
 
craigi said:
The rationale behind it, is that if someone who is unfamiliar with the code wants to do something at the end of the function for all cases, then they can miss a return point and introduce a bug.
I've heard lots of excuses for the "single point of entry / single point of return", but I haven't heard this one before. That's pretty lame.

People who analyse this sort of stuff can estimate how often mistakes like this happen and their cost to a project.
Name one. Citation needed.

Future languages may even make it impossible.
This thread isn't about speculative directions in computer language development. It's about C++.

That said, those future languages will most likely formalize the concepts of preconditions and postconditions. That isn't the case in C++, which is why you will oftentimes find code that implements those preconditions in the form of early exit or throwing an exception.

In addition to those early exits, another common use for multiple returns in C++ is a search function. These two paradigms, using return statements for preconditions and a successful search, are widely used and widely accepted amongst professional C++ programmer.

Can return statements be abused, make code more confusing? Of course. Just because they can do so when used inappropriately does not mean they almost always do. More importantly, there are places where a return statement can enhance readability / understandability.
 
AlephZero said:
How did they know they wanted to do something at the end for all cases, unless they traced all the possible ways they could get to the one return point?

Thinking or assuming they wanted to do something in all cases (e.g. by believing or misunderstanding the documentation, but not actually reading the code) might also be a bug!

When you're working with other people's code, you don't always fully understand the functions that you're modifying nor do you always need to. It's not ideal, but many experienced software developers have experienced, it at some point.

D H said:
I've heard lots of excuses for the "single point of entry / single point of return", but I haven't heard this one before. That's pretty lame.

It's certainly not lame if you're working on very large scale, safety critical projects.

D H said:
Name one. Citation needed.

Jean Ichbiah et al took this very seriously, for example.

D H said:
More importantly, there are places where a return statement can enhance readability / understandability.

Agreed. Very small functions and functions that are clearly structured for early-outs, are good examples. If you care about performance, they can also be used to coax the compiler into generating more optimal code, in certain cases.

Jamin2112 said:
I can do

Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    if (n == 0)
    {
        return false;
    }
    else
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
        return true;
    }
}

or, equivalently,

Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    bool retval;
    if (n == 0)
    {
        retval = true;
    }
    else
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
        retval = false;
    }
   return retval;
}

Regarding the OP, both of those functions are completely horrible. More structure to your programming will certainly help and in this case, a single exit should actually make your code simpler. Perhaps then you'll actually see the bugs in it. I can see 2 reasons why the first function doesn't even work straight away, one very dubious omission and one extra bug introduced by refactoring it for the second function.
 
Last edited:
  • #10
McCabe's static code metric algorithm actually counts function returns as part of determining 'cyclomatic complexity' - a measure of the feasibility of code testing, primarily a result of code branching. It is old.

McCabe T. J., "A Complexity Measure". IEEE Transactions on Software Engineering 1976

My point is not about McCabe's approach, good or bad, but the fact that the algorithm counts "extra" return statements as negative dings the to the overall result. More returns are supposed to be bad. I believe this kind of thing has fostered the idea: 'more than one return in a function is bad'

Also see: http://en.wikipedia.org/wiki/Cyclomatic_complexity
 
  • #11
@craigi - on PF, and in Science in general, a citation means just that: author,( journal or book) title, article title or chapter citation, date.

The most common reference for Jean Ichbiah is understandably: Ada
 
  • #12
jim mcnamara said:
@craigi - on PF, and in Science in general, a citation means just that: author,( journal or book) title, article title or chapter citation, date.

The most common reference for Jean Ichbiah is understandably: Ada

Sure, but I'm already happy with my contribution to the thread. Thank you for your contribution too. Searching for citations to support what we both already know seems fruitless and I'm content for anyone who doubts it to disregard it, out of hand.
 
  • #13
craigi said:
It's certainly not lame if you're working on very large scale, safety critical projects.
That is what exactly what I do: Projects in the MSLOCs that can result in billions of dollars of damages, loss of life, and loss of national prestige.

But don't take my word for it. Let's look at a coding standard for a large scale, safety critical project that has been widely promulgated throughout the large scale, safety critical C++ community, the Joint Strike Fighter C++ Coding Standard (http://www.stroustrup.com/JSF-AV-rules.pdf) (emphasis theirs):
4.13.2 Return Types and Values
AV Rule 113 (MISRA Rule 82, Revised)
Functions will have a single exit point.

Rationale: Numerous exit points tend to produce functions that are both difficult to understand and analyze.
Exception: A single exit is not required if such a structure would obscure or otherwise significantly complicate (such as the introduction of additional variables) a function’s control logic. Note that the usual resource clean-up must be managed at all exit points.​
Note that this is a will rather than a shall requirement, and also note that the rule has an explicit exception.
Jean Ichbiah et al took this very seriously, for example.
That is not a citation.
jim mcnamara said:
McCabe's static code metric algorithm actually counts function returns as part of determining 'cyclomatic complexity' - a measure of the feasibility of code testing, primarily a result of code branching. It is old.

McCabe T. J., "A Complexity Measure". IEEE Transactions on Software Engineering 1976

My point is not about McCabe's approach, good or bad, but the fact that the algorithm counts "extra" return statements as negative dings the to the overall result. More returns are supposed to be bad. I believe this kind of thing has fostered the idea: 'more than one return in a function is bad'

Also see: http://en.wikipedia.org/wiki/Cyclomatic_complexity
Whether return statements raise the cylcomatic complexity is subject to debate. A return statement is equivalent to goto __close_brace. It's just another edge in the local graph. On the other hand throwing an exception, calling exit, or calling some project-specific function that acts like an exception (i.e., the function doesn't return to the caller) is an alternate exit point, and they do bump the complexity.
 
Last edited:
  • #14
For references, the Apple/IBM Taligent project published a Taligent's Guide to Designing Programs, Well Mannered Object Oriented Design in C++

While Taligent is defunct, the guide is still useful for coding standards.

On page 52 Things to Avoid: Don't Use goto

They mention avoiding the use of returning from the middle of a procedure as something that should be reviewed with the project architect. The reasoning is that it could subvert the meaning and correctness of the code requiring you to read all the relevant code to see what's going on.

https://www.amazon.com/dp/0201408880/?tag=pfamazon01-20
 
Last edited by a moderator:
  • #15
jedishrfu said:
On page 52 Things to Avoid: Don't Use goto
The problem with over-simple "rules" is that they are too easy to subvert, as in the OP's code where "goto end-of-function" is replaced by the state variable "retval" which has no other purpose in the code. One of my work colleagues used to call this style of coding "the if-come-from statement" or "backwards programming" (and less complementary names which probably don't meet the PF posting guidelines!)

Of course there are much more creative ways to subvert a "no gotos" or "only one return" rule than he OP's method, as D.H. already mentioned - throwing user-defined exceptions, etc.
 
  • #16
jedishrfu said:
Things to Avoid: Don't Use goto
I've only seen the use of goto "justified" in a tiny number of cases.

Case 1 (very rare): The code gets in trouble deep inside multiply nested loops. This can happen, for example, with some bizarre corner cases in singular value decomposition. While SVD is typically very robust, there are some weird corner cases that defeat this robustness. The problem is that the problem isn't uncovered until deep in the bowels of the SVD algorithm. There would be no problem with this problem if C/C++ had a multilevel break capability. The goto statement provides a way to emulate this missing capability.

Case 2 (much more common): Some fool of a manager has mandated the single point of entry / single point of exit rule, with no exceptions allowed. Some programmer complains that the only alternatives are to add unneeded complexity to the code or to use gotos. The manager's response: "That's right. This is one of those cases where gotos are the preferred implementation." :bugeye:


I for one much prefer to see preconditions dealt with up-front in a manner that clearly calls them out as such. A small (one to three) statement blocks of the form if (simple_test) { log_error(); return; } at the head of a function won't bug me in the least -- so long as those preconditions are clearly documented. Those up-front statements tell a nice Principle of Least Astonishment story.

On the other hand, I've been asked to participate in a code review of a function with over 200 lines of code and a cyclomatic complexity in excess of 20. Those numbers alone bedeviled me beyond belief. That that tangled mess of code of contained buried return or goto statements will just cemented the deal.
 
  • #17
I may be the only one here who really remembers where the "one exit" rule came from.

It was in rebellion to "spaghetti code" - especially prevalent among FORTRAN programmers doing maintenance coding. It came with strict adherence to the basic programming structures ("structure programming").

There is clearly some absurdity to it - as there was with the strict dictates of structure programming. Although it was (and is) true that you could not have spaghetti code with strictly structured programming, what you do get is truly obscure flags to signal which path you want to take.

Personally, I do subscribe to "GOTOless" code - although I wouldn't go so far as to forbid it. My main concern is being able to follow the code - and until you've tackled a system with hundreds of pages, you;re probably not going to catch on to what that means.

Basically, you should realize that there are many ways to implement an algorithm and the one you want to pick is the one that has an easy to follow human-language "story".

As far as single exit coding, like craigi, I commonly deal with safety related or military mission-critical systems and so I give the auditors their due. Some people feel very strongly that there should be only one exit - and I do not care to spend my time fighting them.

So, here is how I would implement the code - allowing for one exit while retaining "sensibility":
Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    bool bOkay;

    //
    // Check valid input (or any other description of why your are checking "n")
    bOkay = n != 0;
    if(bOkay)
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
    }
    return bOkay;
}
Sometime the solution is not quite so simple. Very commonly, there will be many, many exit conditions. The most common solution for avoiding numerous "returns" is to start nesting if statements - one or two levels of nesting for each error condition checked. For example, you're opening a file and you want to check the file name, whether it can be opened, whether a malloc works, whether the filesize is adequate, whether the first 10 bytes are "MyFileType", etc. Wouldn't you love to go "if(!malloc(...)) return MYERR_MALLOC;"?

Here's one not-that-bad method - using an enumeration variable "eErrorState":
Code:
enum { MYERR_NOERROR=0, MYERR_BADNAME, MYERR_NOFILE, MYERR_MALLOC } MYERR;
MYERR eErrorState;

eErrorState = MYERR_NOERROR;
//
// Check filename
if(!eErrorState) {
  ...
  if( error condition ) {
    eErrorState = MYERR_BADNAME;
  }
}
//
// Check file
if(!eErrorState) {
  ...
  if( error condition ) {
    eErrorState = MYERR_NOFILE;
  }
}
...
Not bad, but I prefer this:
Code:
enum { MYERR_NOERROR=0, MYERR_BADNAME, MYERR_NOFILE, MYERR_MALLOC } MYERR;
MYERR eErrorState;

eErrorState = MYERR_NOERROR;
//
// Non-loop to make for easy "break".
for(;;) {
  //
  // Check filename
  ...
  if( error condition ) {
    eErrorState = MYERR_BADNAME;
    break;
  }
  //
  // Check file
  ...
  if( error condition ) {
    eErrorState = MYERR_NOFILE;
    break;
  }
  ...
}
return eErrorState;
 
  • #18
.Scott said:
So, here is how I would implement the code - allowing for one exit while retaining "sensibility":
Code:
template <class T>
bool max (T* arrPtr, size_t n, T highest)
{
    bool bOkay;

    //
    // Check valid input (or any other description of why your are checking "n")
    bOkay = n != 0;
    if(bOkay)
    {
        for (T* i(arrPtr), j(arrPtr + n); i != j; ++i)
            if (*i > highest)
                highest = *i;
    }
    return bOkay;
}

This is a beautiful illustration of 2 things that I was talking about earlier in the thread.

Firstly, it's the simplification that I was referring to that the single exit point paradigm offers in this case.

Secondly, it's easy to see from it how programmers make modifications to functions that they don't fully understand. This shouldn't be taken as a critisism of .Scott, rather just as an observation of how a programmer typically modifies unfamilar functions. In this case he has rightly presumed that he could do no harm to this function by modifying it to have a single exit point, but has also inadvertently copied the 3 serious issues, from the OP's original function, that I was referring to earlier.

Now this is an incredibly simple function. In the case of a more complex function, it really isn't a huge leap of the imagination to see how a programmer attempting make a modification to a function without understanding it in its entirety actually introduces new errors in the false belief that they have done no harm. A more structured programming style defends against these scenarios.

I actually take a very liberal approach to coding standards, but they can serve as a very useful learning resource for inexperienced programmers. Enforcing coding standards is no fun for anyone, but if I were confronted with someone checking in any of the iterations of this function in this thread to a codebase that I was using, I would just delete and rewrite it.
 
Last edited:
  • #19
craigi, while you may see .Scott's solutions as "beautiful", those who advocate early return as the preferred mechanism for dealing with invalid inputs (failed preconditions) will inevitably use a rather different adjective to describe that code. I see what .Scott's wrote as exemplifying why one *should* use early return rather than shun it.This is a programming religion issue. As far as I can tell, there are no studies that compares "single point of entry / single point of return" versus early return with regard to readability, understandability, maintainability, etc. There's only religion. From my experience, mandating religious issues rarely works. Those religious mandates cause managers to tell the programmers who work for them to ignore the programming standards. All of them. I've seen this happen, multiple times.

The "single point of entry / single point of return" rule ranks right up there with regard to causing dissension as do the "no magic numbers" rule (which taken to its extreme results in nonsense such as #define ZERO 0) and the yoda convention rule (which results in inscrutable code such as if (ZERO != number) ...).
 
Last edited:
  • #20
craigi said:
Regarding the OP, both of those functions are completely horrible. More structure to your programming will certainly help and in this case, a single exit should actually make your code simpler. Perhaps then you'll actually see the bugs in it. I can see 2 reasons why the first function doesn't even work straight away, one very dubious omission and one extra bug introduced by refactoring it for the second function.

I feel like an idiot sometimes. I understand that I didn't pass highest as a reference and didn't initialize it inside the function.

How about this:

Code:
template <typename T> T max(T* arr, size_t n)
{
    if (n == 0)  /* I know most people programmers prefer "if (!n)" */
        throw("The max of an empty array is undefined, bro.");

    /* The rest doesn't need to be in an "else" statement, even though the intent of
        the function is to execute the rest of the code only if the "if" condition isn't met */
    T highest = arr[0];
    for (T* i(arr+1), j(arr+n); i != j; ++i) 
    /* Pointer arithmetic starting at the memory address after the first element of the array and
        continuing until one-off-the-end of the array */  
        if (*it > highest)
              highest = *it;
        return highest;
}

I'm sure a C++ purist will have some fancier routine that involves forward iterators, recursion, etc.
 
  • #21
D H said:
craigi, while you may see .Scott's solutions as "beautiful", those who advocate early return as the preferred mechanism for dealing with invalid inputs (failed preconditions) will inevitably use a rather different adjective to describe that code. I see what .Scott's wrote as exemplifying why one *should* use early return rather than shun it.

This is a programming religion issue. As far as I can tell, there are no studies that compares "single point of entry / single point of return" versus early return with regard to readability, understandability, maintainability, etc. There's only religion. From my experience, mandating religious issues rarely works. Those religious mandates cause managers to tell the programmers who work for them to ignore the programming standards. All of them. I've seen this happen, multiple times.

The "single point of entry / single point of return" rule ranks right up there with regard to causing dissension as do the "no magic numbers" rule (which taken to its extreme results in nonsense such as #define ZERO 0) and the yoda convention rule (which results in inscrutable code such as if (ZERO != number) ...).
I agree. My motivation for creating such code is to placate high priests.

The real problem is that there is such a thing as "bad code" - as demonstrated by the widespread success of computer viruses that exploit bad code. This real problem motivates some managers to establish "coding standards" to prohibit "bad code". Unfortunately, you can't turn bad cooks into good cooks by forcing them to hold their cooking utensils in special aesthetically graceful ways. It may make the cooking look better - but you'll still get indigestion.
 
  • #22
Jamin2112 said:
I feel like an idiot sometimes. I understand that I didn't pass highest as a reference and didn't initialize it inside the function.

How about this:

Code:
template <typename T> T max(T* arr, size_t n)
{
    if (n == 0)  /* I know most people programmers prefer "if (!n)" */
        throw("The max of an empty array is undefined, bro.");

    /* The rest doesn't need to be in an "else" statement, even though the intent of
        the function is to execute the rest of the code only if the "if" condition isn't met */
    T highest = arr[0];
    for (T* i(arr+1), j(arr+n); i != j; ++i) 
    /* Pointer arithmetic starting at the memory address after the first element of the array and
        continuing until one-off-the-end of the array */  
        if (*it > highest)
              highest = *it;
        return highest;
}

I'm sure a C++ purist will have some fancier routine that involves forward iterators, recursion, etc.


1 old bug which I'd still argue wouldn't have existed if your code had a more structured style.

1 new bug, but to be fair it looks like a typo.

They're both compile errors so running it through a complier will throw them up.

Don't worry about forward iterators or recursion, but if you want to improve on it, pay particular attention to the use of copy constructors. If T is a built-in type then it makes no difference, but for class types things get more complicated. You've actually hit on a little quirk of C++ called "named return value optimisation", which means that your function can actually have different behaviour on different compilers! You can write this entire function without involving a single copy constructor, which might serve as a useful exercise.

Also, think about your motivation for using c++ exceptions. If the only reason is to dodge the single exit point debate, then it's a heavy price to pay. The bottom line is that you should be mindful of where you put your exit points. You can argue it either way and for such a small function it makes very little difference.
 
Last edited:
  • #23
You're also using the assignment operator for T a lot more than necessary:

Code:
    T highest = arr[0];
    for (T* i(arr+1), j(arr+n); i != j; ++i) 
    /* Pointer arithmetic starting at the memory address after the first element of the array and
        continuing until one-off-the-end of the array */  
        if (*it > highest)
              highest = *it;
        return highest;
Why not just keep track of the index of the maximum, and then at the end, return the array element at that index? Something like

Code:
size_t idxOfMax = 0;
for (size_t i = 1; i < n; i++)
    if (arr[i] > arr[idxOfMax])
        idxOfMax = i;
return arr[idxOfMax];
 
  • #24
Every rule has an exception. The example given is trivial and thus, it does not harm to return from 2 different places. However, for long subroutines or functions, returning from multiple places can lead to difficult-to-read code. The real point made by Code Complete, the book famous for promulgating this rule, is to make your code easily understandable to any outsider who looks at it, or might have to maintain it in the future. As long as you keep this principle firmly in mind, you'll be OK.

One advantage to returning from a single point can be if you are logging progress--the code which logs progress need only be in one place. After many years of coding experience, I began logging progress in all my code. This enabled me to troubleshoot when I got unexpected reports of errors from users--I could see what they had been doing when the error occurred. So I logged, not just errors, but basic calls (and results returned). This had to be done efficiently but was a capability well worth developing. I always log as I enter and leave a function. The slight overhead of this has been well worth it, and if the overhead cannot be afforded, then you can make the logging itself have an on/off capability. But I found it held me to the discipline of having a single point of return.

Some people will fight this, but I am very, very experienced at writing user interface code that goes to a lot of users. They always, always, encounter something what wasn't caught in testing, and mechanism such as single point of return, with error logging, can save your bacon when that happens. My current group of a dozen or so users have grown so accustomed to this that they now automatically send me their log files along with any trouble report. Saves a mountain of time for everyone. 99% of the time, the log file directs me quickly to the problem.
 
Last edited:
  • #25
harborsparrow said:
I always log as I enter and leave a function. The slight overhead of this has been well worth it, and if the overhead cannot be afforded, then you can make the logging itself have an on/off capability. But I found it held me to the discipline of having a single point of return.
Why not instantiate an object whose constructor and destructor log the entry/exit? Then it's irrelevant whether you have a single point of return or not. I've done something similar when measuring the amount of time spent in various functions.
 
  • #26
This rule is much older than Code Complete (a book that should be on every profession programmer's essential reading list). Steve McConnell was reiterating what *some* held as common wisdom. Here's what McConnell wrote in Code Complete:

Minimize the number of returns in each routine. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.

Use a return when it enhances readability. 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.​

Even McConnell left an out. (The authors of the JSF coding standards similarly left an out.) If return statements enhance readability and understandability, use them. If all they do is obfuscate, don't use them. A return statement buried deep in some convoluted logic has zero redeeming value.

Personally, I **hate** this rule on the basis that it causes more harm than good. The underlying intent is certainly good, but good intentions are what the road to the underworld is paved with.
 
  • #27
jbunniii said:
Why not instantiate an object whose constructor and destructor log the entry/exit? Then it's irrelevant whether you have a single point of return or not. I've done something similar when measuring the amount of time spent in various functions.

This is a way to log. It might be less obvious to someone reading the code. And finding the deconstructor is not always easy.

There are also code injection technologies, if tracing code execution is all one is after.

I'm after a lot more than simply tracing execution. I may also log returned values upon exit. I'm always thinking about what I'd need to see in the log if a trouble report comes.

Personally, I like to stick to the "single point of return" rule most of the time, because I've found it helps me read the code again late--especially if I have to come back to it after a lot of time has lapsed.
 
  • #28
harborsparrow said:
Personally, I like to stick to the "single point of return" rule most of the time, because I've found it helps me read the code again late--especially if I have to come back to it after a lot of time has lapsed.

(bolding mine)

I think most of us agree with the general sentiment. As DH wrote, problems start when the rule becomes a religion.

IMHO that's the problem with most of the similar rules used in programming. They work great most of the time, but there are moments when religiously sticking to them just produces code that becomes unreadable, or unnecessarily complicated.
 
  • Like
Likes 1 person
  • #29
Jamin2112 said:
I know someone at Google who says you should never have more than 1 return statement in a function. That seems ridiculous to me.

In some languages that is OK.
 
  • #30
gmar said:
In some languages that is OK.
That's not in dispute. What this thread was about was whether it was good practice to have exactly one return statement in a function. As D H has said, this "rule" has become something of a religious controversy, akin to the controversy about where the opening brace for a for loop, while, loop, if block, etc. should go: on the same line or on a new line.
 

Similar threads

  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 45 ·
2
Replies
45
Views
5K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 8 ·
Replies
8
Views
4K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K