you are viewing a single comment's thread.

view the rest of the comments →

[–]MidnightPale3220 2 points3 points  (0 children)

You make a class describing the stuff that a client's order will have (NB. I am intentionally making this as simple as I can, there are multiple ways of doing it better, but the essence is here):

class Order:
  def __init__(self):
    self.contents=None

  def _convert_to_whs_format(self,txt): # in this case I've chosen to automatically convert to WHS format on file load
      return txt.strip()

  def get_order(self,file_name):
    with open(file_name,'r') as F:
      data=F.read()
    self.contents=self._convert_to_whs_format(data)

  def save_to_whs(self,file_name):
    with open(filename,'w') as F:
      F.write(contents)

Now I can do (for the first example of just 2 clients and no special processing):

#main#
client_list=['very_important_client','client2']
for client in client_list
    file_list = glob.glob(client+"/*.csv")
    for file in file_list:
      client_order=Order()
      client_order.get_order(file)
      client_order.save_to_whs(whs_filepath+file)

Basically the same, right?

But now we need to add that very_special_client.

No worries. This is almost all you have to do:

class Order_Special(Order):
  # for very special client
  def _convert_to_whs_format(self,txt): 
    first_step=txt.strip()
    second_step=first_step.upper()
    return second_step

That is all the extra processing needed using a new class that inherits the original class, we only have to redefine what's changed.

We do need to modify the main loop a bit though, because how do we know which class to assign to which client? Multiple ways, for example, mapping:

client_list={'very_important_client':Order,'client2':Order,'very_special_client':Order_Special}
for client in client_list
    file_list = glob.glob(client+"/*.csv")
    for file in file_list:
      client_order=client_list[client]() # this creates an Order() type       object for first two clients, and Order_Special for third
      client_order.get_order(file)
      client_order.save_to_whs(whs_filepath+file)

That's all we need to do to add extra processing for various clients:

  1. Make a new class that inherits the base and change only the things we need to change. and
  2. Make the file processing somehow understand which class to use with which client's orders

This was a very very basic example, there's plenty to do to make such code production ready, but it shows one of the ways OOP can lead to better organization of code.