65.9K
CodeProject is changing. Read more.
Home

The goto-less goto!

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (11 votes)

Jan 25, 2011

CPOL
viewsIcon

41884

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;
}
...