Click here to Skip to main content
16,016,736 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

The goto-less goto!

Rate me:
Please Sign up or sign in to vote.
4.95/5 (12 votes)
25 Jan 2011CPOL 41.8K   4   33
Alternative 2 can be enhanced by returning a booleen value if we want to code something similar to the original example. A (early) return value of false would indicate a failure which could then be handle by checking the function result.if (!DoAllActions()){ ...
Alternative 2 can be enhanced by returning a booleen value if we want to code something similar to the original example. A (early) return value of false would indicate a failure which could then be handle by checking the function result.

if (!DoAllActions())
{
   DoFailedCleanup();
}

bool DoAllActions()
{
   if (condition1_fails)
      return false;
   if (condition2_fails)
      return false;
   ...
   if(!conditionN_fails)
      retrun false;
   PerformActionOnAllSuccess();
   DoNormalCleanup();
   return true;
}


Alternatively, if each action are independant, a variation like this might be more appropriate:
if (DoAction1() && 
    DoAction2() && 
    ... && 
    DoActionN())
{
   PerformActionOnAllSuccess();
   DoNormalCleanup();
}
else 
{
   DoFailedCleanup();
}

bool DoAction1()
{
   bool condition1_fails = ...;
   return !condition1_fails;
}
...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
Programmer at Maid LABS from 2003 (www.maidlabs.com)

Programmer-Analyst at Viasat Geo Technoligies from 1995 to 2002 (www.viasat-geo.com).

I have studied at École Polytechnique de Montréal in computer engineering.

Comments and Discussions

 
GeneralMy vote of 5 Pin
pasztorpisti26-Aug-13 9:34
pasztorpisti26-Aug-13 9:34 
GeneralRe: Surely anyone can program whatever he wants for himself and ... Pin
Wolfgang_Baron7-Apr-11 6:07
professionalWolfgang_Baron7-Apr-11 6:07 
GeneralRe: Clearly we have difference experiences - and debuggers. One ... Pin
EFEaglehouse7-Apr-11 4:05
EFEaglehouse7-Apr-11 4:05 
GeneralRe: The first person wanting to add a debug statement at the end... Pin
Wolfgang_Baron7-Apr-11 1:45
professionalWolfgang_Baron7-Apr-11 1:45 
GeneralSorry, but in C++ at least, not being able to add a debug st... Pin
jefito12-Apr-11 3:02
jefito12-Apr-11 3:02 
GeneralMultiple returns look clear only to those, who have written ... Pin
Wolfgang_Baron9-Feb-11 5:32
professionalWolfgang_Baron9-Feb-11 5:32 
GeneralRe: Never say never. Sometimes the clearest code is the shortest... Pin
EFEaglehouse5-Apr-11 4:32
EFEaglehouse5-Apr-11 4:32 
GeneralIn fact, with this pattern where the complex function is spl... Pin
Philippe Mori9-Feb-11 5:00
Philippe Mori9-Feb-11 5:00 
GeneralReason for my vote of 1 People who put more than one return ... Pin
Wolfgang_Baron9-Feb-11 4:35
professionalWolfgang_Baron9-Feb-11 4:35 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti26-Aug-13 9:27
pasztorpisti26-Aug-13 9:27 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron7-Oct-13 3:08
professionalWolfgang_Baron7-Oct-13 3:08 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti7-Oct-13 3:24
pasztorpisti7-Oct-13 3:24 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron7-Oct-13 5:10
professionalWolfgang_Baron7-Oct-13 5:10 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti7-Oct-13 5:39
pasztorpisti7-Oct-13 5:39 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron7-Oct-13 13:08
professionalWolfgang_Baron7-Oct-13 13:08 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti7-Oct-13 22:37
pasztorpisti7-Oct-13 22:37 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron9-Oct-13 14:59
professionalWolfgang_Baron9-Oct-13 14:59 
Quote:
... and 1-2 sentences later:

First the general statement, then the summary of this kind of lengthy conversation, why is that worth a quote?
Quote:
Spaghetti and multiple returns are two different things.

They both have messy, hard to analyze flows of control. Throw in a few exceptions and gotos and you are ready to rumble!
Quote:
A function can be spaghetti with both multiple returns and with single point of return but with so many years of experience you probably know this.

Yes, finally something we agree on Smile | :) . However, I am not willing to obscure the structure of my program by introducing multiple returns. I want easy to read and quickly to understand code.
Quote:
Could you please make my spaghetti function below more readable without multiple returns because I'm lazy to think too much:

Well, this opens a can of worms. You created this little example for the usage of a number of functions. Maybe these functions do not provide the right interface for nicely integrating them in a function concerned with flow of control. I started to experiment with your example and found a number of ways to deal with that kind of design. The best way, of course, is to rethink your program. You will not write a beautiful part of your software, if the rest does not fit. So maybe, your low level functions should return a boolean, indicating an error, so you can chain them together with lazy evaluating || or &&. You can also write a little adapter, which collects the error value while computing the result. Modern compilers will inline that extra code, so your program will not slow down a lot. I benchmarked a lot of variants on Visual C++ 10 and gcc 4.7.3. Gcc gave the fastest execution for the following kind of code, even though it does not use lazy evaluation (I know, lazy evaluation has to be done by the functions):
typedef float vtype;

vtype FuncB1( bool & aSuccess );
vtype FuncB2( bool & aSuccess );
vtype FuncB3( bool & aSuccess );

vtype FuncF() {
    vtype result;
    bool l_success = true;

    result = FuncB1( l_success ) + FuncB2( l_success ) + FuncB3( l_success );
    if (!l_success) result = 0;
    return result;
}

An example for an adapter would be:
static inline bool add_nn( vtype & aResult, vtype aValue ) {

    aResult += aValue;
    return aValue < 0;
}

vtype FuncH() {
    vtype   result = 0;

    if (add_nn( result, Func1() )
            || add_nn( result, Func2() )
            || add_nn( result, Func3() ))
    {
        result = 0;
    }
    return result;
}

If you prefer lambdas and C++11 style to stow away the adapter code without a global definition, you can do:
vtype FuncI() {
    vtype   result = 0;
    auto    l_add = [&result]( vtype aValue ) -> bool {
        result += aValue;
        return aValue < 0;
    };

    if (l_add( Func1() ) || l_add( Func2() ) || l_add( Func3() )) {

        result = 0;
    }
    return result;
}

Now, I think I spent enough time on this, so if I don't answer, I am busy doing other stuff and may not return for some time. Anyhow, feel free to continue the experiments and introduce explicit logic to your code, so that the reader has to spend less time analyzing what the code does in its entirety.
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Philippe Mori9-Oct-13 17:35
Philippe Mori9-Oct-13 17:35 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti9-Oct-13 22:07
pasztorpisti9-Oct-13 22:07 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Philippe Mori10-Oct-13 2:24
Philippe Mori10-Oct-13 2:24 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti10-Oct-13 2:46
pasztorpisti10-Oct-13 2:46 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron9-Oct-13 22:29
professionalWolfgang_Baron9-Oct-13 22:29 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Philippe Mori10-Oct-13 2:36
Philippe Mori10-Oct-13 2:36 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
pasztorpisti9-Oct-13 22:18
pasztorpisti9-Oct-13 22:18 
GeneralRe: Reason for my vote of 1People who put more than one return ... Pin
Wolfgang_Baron9-Oct-13 22:59
professionalWolfgang_Baron9-Oct-13 22:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.