vendredi 17 février 2023

Abstract method's parameters aren't all used in the child classes

class parent:
  @abstractmethod
  def process(self, x, y, z):
    pass

  def post_process(self):
    self.process(x, y, z)

class child1(parent):
  def process(self, x, y, z):
    # do stuff with x and y, and ignore z

class child1(parent):
  def process(self, x, y, z):
    # do stuff with x, y, z

This is an existing design in the codebase I am working in. I don't like it for readability because the variable z isn't used for all child classes, and I suspect it was designed this way so that post_process doesn't need to check which child class is calling.

I am thinking of changing it to:

class parent:
  def post_process(self):
    if isinstance(self, child1):
      self.process(x, y)
    elif isinstance(self, child2):
      self.process(x, y, z)

class child1(parent):
  def process(self, x, y):
    # do stuff with x and y

class child1(parent):
  def process(self, x, y, z):
    # do stuff with x, y, z

This does the case work of checking which child class is calling post_process, but I feel it is better for readability and avoids having to pass in unnecessary arguments. Are there other ways besides this to resolve this issue?

Aucun commentaire:

Enregistrer un commentaire