where to put conditional in chain of operations

  softwareengineering

I have two types of input data which will go through a number of steps for processing. The processing differs only in one of those steps, e.g.:

TypeX: A() -> B() -> Cx() -> D()

TypeY: A() -> B() -> Cy() -> D()

What’s a good way to approach structuring this type of code? For example, I could branch right at the start:

def main
  if(d is type X) process_type_X() else process_type_Y()

def process_type_X(x)
  D(Cx(B(A(x))))

def process_type_Y(y)
  D(Cy(B(A(x))))

Or at the specific step

def process_data(d)
   d1 = A(d)
   d2 = B(d1)
   d3 = if (d is type X) Cx(d2) else Cy(d2)
   D(d3)

It seems like the first way is clearer, it indicates these are two different types of data and are processed differently up front. On the other hand, I imagine if the function calls were more nested and the difference was in some small leaf function, you’d have a lot of duplication.

Your second example contains duplicated code. You can remove it like this:

def process_data(d)
   C = (if d is type X) Cx else Cy
   d1 = A(d)
   d2 = B(d1)
   d3 = C(d2)
   D(d3)

However, given the condition if d is type X, it seems like the condition itself should move to the actual type. That is, if you need to use Cx if d is of type X, and Cy if d is of type Y, then Cx and Cy are likely to belong to the actual X and Y classes.

Your code therefore becomes:

def process_data(d)
   d1 = A(d)
   d2 = B(d1)
   d3 = d.C(d2)
   D(d3)

which is much more readable.

2

LEAVE A COMMENT