0

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.

5

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
  • 3
    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
  • Sorry about the delay and thanks for answering. In my particular case I don't think I have the option of actually representing the different data with different types (without huge refactoring on a codebase I'm new to), although I agree that generally makes sense for this problem.
    – allstar
    Feb 9 '21 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.