The goto-less goto!






4.95/5 (11 votes)
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; } ...