# where to put conditional in chain of operations

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.

``````def process_data(d)
• Basically you need object-oriented polymorphism. On a related note, you can accomplish this in a functional language using `def process_data(d, c)` where `c` is a function pointer or reference. The caller determines which specific implementation of `c` is needed (i.e. Cx or Cy). Feb 5 '21 at 19:41