Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

The goto-less goto!

, 28 Feb 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Member 4694807

Germany Germany
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 3 This is good, too, but has the disad... PinmemberEFEaglehouse5-Apr-11 5:03 
GeneralReason for my vote of 5 This is the cleanest separation of '... PinmemberStefan638-Mar-11 1:41 
Reason for my vote of 5
This is the cleanest separation of 'goto conditions' I've seen, and - in my opinion - the best to maintain.
 
I prefer the second alternative, but I suppose the first is viable as well, depending on the circumstances.

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 28 Feb 2011
Article Copyright 2011 by Member 4694807
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid