cdonner
cdonner

Reputation: 37668

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

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?

Upvotes: 0

Views: 142

Answers (2)

Rian Schmits
Rian Schmits

Reputation: 3206

Doesn't this solve the redundancy:

if A
   prepareprocessingfunction()
   do A logic
else if B
   prepareprocessingfunction()
   do B logic
else if C
   prepareprocessingfunction()
   do C logic
// else do nothing
end

prepareprocessingfunction() {
   prepare processing
}

Upvotes: 0

Guillaume
Guillaume

Reputation: 1032

Can't you do

if (A, B, or C)
   prepare processing 
   if A
      do A logic
   else if B
      do B logic
   else if C
      do C logic
end

? Maybe I misunderstood.

Edit: zzz, your edits messed me up. If you don't want it to evaluate A,B,C twice then do

x = func returnCase() //returns a,b, or c
if x != None
   prepare processing
   do Case

Upvotes: 1

Related Questions