Definition:
Software entities should be open for extension but closed for modification.
Explanation:
The Open/Closed Principle advocates designing modules that can be extended to incorporate new functionality without altering their existing code. This is typically achieved through abstraction and polymorphism, allowing new behaviors to be added via subclasses or implementing interfaces. Adhering to OCP minimizes the risk of introducing bugs when enhancing features and promotes scalability.
Example:
Suppose you have a Shape class with a method to calculate the area. To add new shapes without modifying the existing Shape class:
# Adheres to OCP
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2