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

The goto-less goto!

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
28 Feb 2011CPOL 7.2K   2   2
My favorite is a variant of alternative 2.{ ... DoInit(); status=DoAllActions(); DoCleanup(status); ...}int DoAllActions(){ if (condition1_fails) return status1; ... if (condition2_fails) return status2; ... if(conditionN_fails) ...
My favorite is a variant of alternative 2.

{
  ...
  DoInit();
  status=DoAllActions();
  DoCleanup(status);
  ...
}

int DoAllActions()
{
   if (condition1_fails)
      return status1;
   ...
   if (condition2_fails)
      return status2;
   ...
   if(conditionN_fails)
      return statusN;
   PerformActionOnAllSuccess();
   return statusSUCCESS;
}

DoCleanup(status)
{
 if(status==statusSUCCESS)
   DoNormalCleanup();
 else
   DoFailedCleanup();
}


Avoiding retuns or additional functions, I would write the following code:

{
   if(condition1_fails)
      status=status1;
   else if(condition2_fails)
      status=status2;
   ...
   else if(conditionN_fails)
      status=statusN;
   else
   {
      PerformActionOnAllSuccess();
      status=statusSUCCESS;
   }
   if(status==statusSUCCESS)
     DoNormalCleanup();
   else
     DoFailedCleanup();
}


This form of "else if" is like a case-statement, but much more flexible because you can replace ConditionN by a function-call instead of testing only one value. This untypical arranging of if and else makes clear what the programmer wanted. But often, you have to do a lot of work between the tests which cannot be put into a single function so the first variant is the best and most flexible, I think.

License

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


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 3 This is good, too, but has the disad... Pin
EFEaglehouse5-Apr-11 4:03
EFEaglehouse5-Apr-11 4:03 
GeneralReason for my vote of 5 This is the cleanest separation of '... Pin
Stefan_Lang8-Mar-11 0:41
Stefan_Lang8-Mar-11 0:41 

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.