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

Tagged as

The goto-less goto!

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

Share

About the Author

Philippe Mori
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

 
GeneralReason for my vote of 5 IMHO the superior technique. I don't... Pinmemberdmjm-h31-Jan-11 7:31 

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 | Mobile
Web04 | 2.8.140814.1 | Last Updated 25 Jan 2011
Article Copyright 2011 by Philippe Mori
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid