Conditions with common logic: question of style, readability, efficiency, ...

Posted by cdonner on Stack Overflow See other posts from Stack Overflow or by cdonner
Published on 2011-02-08T22:52:27Z Indexed on 2011/02/08 23:25 UTC
Read the original article Hit count: 403

I have conditional logic that requires pre-processing that is common to each of the conditions (instantiating objects, database lookups etc). I can think of 3 possible ways to do this, but each has a flaw:

Option 1

if A
   prepare processing
   do A logic
else if B
   prepare processing
   do B logic
else if C
   prepare processing
   do C logic
// else do nothing
end

The flaw with option 1 is that the expensive code is redundant.

Option 2

prepare processing  // not necessary unless A, B, or C
if A
   do A logic
else if B
   do B logic
else if C
   do C logic
// else do nothing
end

The flaw with option 2 is that the expensive code runs even when neither A, B or C is true

Option 3

if (A, B, or C)
   prepare processing 
end

if A
   do A logic
else if B
   do B logic
else if C
   do C logic
end

The flaw with option 3 is that the conditions for A, B, C are being evaluated twice. The evaluation is also costly.

Now that I think about it, there is a variant of option 3 that I call option 4:

Option 4

if (A, B, or C)
   prepare processing 
   if A
      set D
   else if B
      set E
   else if C
      set F
   end
end

if D
   do A logic
else if E
   do B logic
else if F
   do C logic
end

While this does address the costly evaluations of A, B, and C, it makes the whole thing more ugly and I don't like it.

How would you rank the options, and are there any others that I am not seeing?

© Stack Overflow or respective owner

Related posts about coding-style

Related posts about conditional