'Inheritance - calling the base class method logic but with some tweaks needed for each derived class

In the base class Figure the nearly_common_figure_logic is shared by all derived classes with some specialisation required::

  • 2 child classes require some distinct additional steps
  • 1 child class does not require the step at all

Two ways to solve this I have figured out are:

  1. have base class check some attribute to understand which logic to apply (bad as the base class should not be doing it so I have commented it out)
  2. have the base class call my_specific method defined in the inherited classes (less bad but still not great since class Line does not need that method so violation of Interface Segregation Principle)

What's a good way to solve it that does not violate design and clean code principles?

class Figure:
    
    def __init__(self):
        self.sides = None
    
    def nearly_common_figure_logic(self):
        print("1. Do the generic thing for all figures, Part I")
        print("2. Do the generic thing for all figures, Part II")
        
        # if self.sides == 3:
        #     print("3. Do a sligtly specialised triangle step, Part III")
        # elif self.sides == 4:
        #     print("3. Do a sligtly specialised square step, Part III")   
        
        self.my_specific()
        
        print("4. Do the generic thing for all figures, Part IV")
        print("5. Do the generic thing for all figures, Part V")


class Line(Figure):
    
    def __init__(self):
        self.sides = 0
    
    # this method is not really needed here but added to make the method in the
    # base class work
    def my_specific(self):
        pass


class Square(Figure):
    
    def __init__(self):
        self.sides = 4
    
    def my_specific(self):
        print ("3. Do a sligtly specialised square step, Part III")


class Triangle(Figure):
    
    def __init__(self):
        self.sides = 3
    
    def my_specific(self):
        print ("3. Do a sligtly specialised triangle step, Part III")


l = Line()
s = Square()
t = Triangle()

print("Square:")
s.nearly_common_figure_logic()
print("Triangle:")
t.nearly_common_figure_logic()
print("Line:")
l.nearly_common_figure_logic()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source