tags:

views:

143

answers:

8

Hi, I read that both multiple returns and multiple goto statements are bad programming practice. I have a function which can detect some 8 types of errors. In case of error, should i return error code or should i use goto statment to go to end of function and return from there. Whenever memory freeing is required before returning from function, i thought it would be better to have a goto end and free the memory at the end of the function(so that only one free is enough in function)

However, In my function, memory is not allocated. In this case which one is preferable ? Multiple returns or multiple goto statements ? Or can we avoid both ?

EDIT: Some way to avoid both is, pass parameter to function which can store errorType. Samething can be checked inside function before proceeding further. But this too makes the code ugly.

+3  A: 

I am of the opinion that multiple return statements are fine, and when dealing with memory allocation and freeing, using things like smart pointers that handle the memory management for you are almost always worth it.

MBennett
+1 for multiple return statements being fine; I've seen programmers refusing to use it, and instead resort to 5 or more levels of indentation in if statements, which makes for a much harder read than multiple returns.
stijn
programs are sometimes hard to debug if you have multiple returns from a function
Devil Jin
+3  A: 

Avoid doing memory management yourself. Chances are you are using the default allocator and new will throw exceptions. Write C++ code following RAII and wrap all code that allocates resources in classes. Then there is no need for manually freeing memory

obelix
+1  A: 

I wouldn't recommend goto as you will be severely shunned (even though I think there are exceptions where goto is a reasonable approach).

Multiple returns are fine. I tend to reserve these for guard clauses. This is where the first part of the function implementation consists of one or more if(x) return; statements. These attempt to identify bad parameters or other error conditions that negate the need to do any more processing.

The guard clauses should help keep the if-else nesting to a minimum for the rest of the code. I do try to limit things to one return for this section by using a temp result. If you still find that nesting is deep or multiple returns would help, then the function may be trying to do too much and should be refactored into multiple helper functions.

Arnold Spence
Goto is actually *great* if you are writing C code and/or can't use exceptions. Instead of throwing, you `goto` into a cleanup block. For more examples of the correct use of goto, see the Linux kernel.
asveikau
Yes, that is one goto pattern I agree with.
Arnold Spence
+2  A: 

Any method / procedure that has multiple goto or return statements can be transformed into one (or more) other methods that have one point of exit, and no goto statements.

For example:

void proc1(...) {
    // allocate thing
    if (x) {
        ...
        // free thing
        return;
    } 
    ...
    // free thing
    return;
}

can be rewritten as:

void proc1(...) {
    // allocate thing
    proc1a(...);
    // free thing
}

void proc1a(...) {
    if (x) {
        ...
        return;
    } 
    ...
    return;
}

With a little bit of thought, you can avoid both the duplicated memory management for each return and the (IMO kludgy) goto workaround.

Your choice of alternative should ultimately be motivated by the goals of making the code readable and maintainable, rather than by dogma about multiple returns or gotos being bad.

Stephen C
+1 is due where it is due. I use for the task gotos often - but only in C-like code. But even for the C code, I prefer to separate resource management from the business logic.
Dummy00001
A: 

You could use another parameter for the error just as you said OR even returning a struct that keeps all the results. I once wrote a BTree class and used the struct method to return search_results (I kept things like: Did_I_find_it or where's the position of the element and a bunch of other things.) I prefer to think thet parameters are for input and return statements for the output of the function.

Goto should really be avoided. It's the most messy solution.

Auxiliary
A: 

NONE I would say

  • Probably you may want to split your method into smaller methods

  • People sometimes use do{..}while(0) loops with break combination. This makes sure that the method returns only from one place. Use of goto should be avoided unless you do not see any other option.

Sample Code:

int myMethod(){
  int retval = 0;
  do{
      if(...){
         retval = 1;
         break;
      }
      else if(...){
         retval = 2;
         break;
      }
      else{
         retval = 3;
         break;
      }
   }while(0);
  return retval;
}
Devil Jin
`LOL` at your `use` of the `code` span :)
Timwi
it helps you not to miss out the key components. I `LIKE` it :)
Devil Jin
+2  A: 

If you look at how goto is used in C code, such as the Linux kernel, it is used to do resource cleanup prior to returning from a function. Multiple labels are used to deallocate resources in the reverse order of acquisition, with earlier parts of the code jumping to later goto labels.

In C++, instead you should use RAII to manage your resources. Then you can use multiple return statements and any needed cleanup will happen automatically.

However if you are detecting many different types of errors, your functions/methods may be exhibiting low cohesion and you may want to consider splitting your functions/methods up into smaller units. This can make error handling more difficult as you may now have more complex return paths, so to avoid this cumbersome error handling, look to use exceptions instead of error return values. This will dovetail nicely with RAII to clean up resources automatically.

camh
A: 

Note that using goto may disable some compiler optimizations in your function. Thus, using goto without a good reason may lead to less efficient code.

Besides, IMHO, using return statements instead of multiple goto statements results in a more readable/reviewable code. With goto's you have to search the target labels and make sure nobobdy really obfuscates the code with goto's.

And, in C++, you have powerful language constructs like exceptions and objects with destructors that do resource cleanup on scope-exit - thus, the use of goto's is really limited.

maxschlepzig