Open/Closed Principle
Open/Closed Principle: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. Here is an example of a function that violates the Open/Closed Principle by requiring modification every time we want to add a new shape.
def shape(shape):
if shape == 'circle':
draw_circle()
elif shape == 'square':
draw_square()
elif shape == 'triangle':
draw_triangle()
else:
raise Exception('Unknown shape')
To adhere to the Open/Closed Principle, we can use inheritance and
polymorphism to extend the functionality of the area function without modifying it:
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
def calculate_area(shape):
return shape.area()