mardi 14 février 2023

Is it bad design to have an abstract method with a parameter that isn't used by all inherited classes?

There is an inheritance structure at my work's codebase, where there are 2 inherited classes that define an method get_df, however one of the parameters, var2, is unused in the second inherited class. I believe it was designed this way so that when get_df is called in process, it can use polymorphism rather than if/else checks.

Here's the skeleton code of what I'm referring to:

class base_class:
  @abstractmethod
  def get_df(self, var1, var2):
    pass

  def process(self):
    # obtain var1, var2
    self.get_df(var1, var2)

class inherited_class1:
  def get_df(self, var1, var2):
    # define get_df

class inherited_class2:
  def get_df(self, var1, var2):
    # define get_df, but var2 is not used here
  

In general, is this kind of design frowned upon since you're passing in an argument that's unused?

An alternative design would be to get rid of the abstract method and do if/else checks:

class base_class:
  def process(self):
    if self is inherited_class1
      # obtain var1, var2
      self.get_df(var1, var2)
    else # self is inherited_class2
      # obtain var1
      self.get_df(var1)

class inherited_class1:
  def get_df(self, var1, var2):
    # define get_df

class inherited_class2:
  def get_df(self, var1):
    # define get_df
  

Are there other approaches that I should consider?

Aucun commentaire:

Enregistrer un commentaire