Link to home
Start Free TrialLog in
Avatar of FranklinRaj22
FranklinRaj22

asked on

Nested if/else performing the same block of code - Efficient method

All

I have to check multiple cases and update an error message but will have to perform the same piece of activity  . For example
IF(a) {do a();do z();}else if (b){do b();do z();}else if(c){do c();do z();}
instead of calling z() thrice what is the best way to do it ?

I can always hav a Boolean flag and validate it , is that the best way or is there a better way to accomplish this ?
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

if you always always call z(), after calling a() or b() or c(), then you could add the call to z() to each of a(), b() and c().

then your resulting if statement would be :
IF(a) {do a();}else if (b){do b();}else if(c){do c();}
That already looks like the most efficient evaluation to me.

buttersk's is fine, saving that future readers of the code may find it opaque.

Or maybe you could accommodate something on the lines of :

do(z);
if(a){do(a);}else if(b){do(b);}else if(c){do(c);}
else{undo(z);}
Avatar of FranklinRaj22
FranklinRaj22

ASKER

Is using a boolean flag in the conditions and checking the flag and calling z() is better than these ??
ASKER CERTIFIED SOLUTION
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial