Understanding The Open Closed Principle Watermark Watermark
Understanding The Open Closed Principle Watermark Watermark
Key Rules
1. Use Abstraction: Implement abstract classes or interfaces to define
behaviors without specifying the concrete implementations. This allows
different modules to derive from these abstractions to introduce new
behaviors.
2. Favor Composition Over Inheritance: Prefer using composition to
assemble classes dynamically rather than relying solely on inheritance,
which can lead to tightly coupled code. This allows you to swap out
components without altering existing code.
3. Design for Extension: Structure your classes and modules with
anticipated extensions in mind. Identify points where new features can be
added and design your code to accommodate these potential changes.
4. Version Control: Use versioning of APIs and modules, allowing the
introduction of new functionalities while maintaining backward
compatibility with existing implementations.
314CS23078
5. Closed for Modification: Ensure that public methods of a class are stable
and do not change frequently. Changes should be encapsulated in new
classes or modules rather than modifying existing ones directly.
Improved Maintainability
By adhering to the OCP, code becomes more maintainable. When changes are
required, developers can extend existing structures without altering the core
functionality. This separation of concerns leads to a cleaner architecture, as
adjustments can occur in isolation, minimizing the risk of breaking existing
features.
314CS23078
Ease of Adding New Features
The OCP simplifies the process of implementing new features. For instance,
when a new feature is required, developers can create new classes or modules
instead of modifying existing ones. This fosters an agile environment where
innovation can happen swiftly without the fear of destabilizing the existing system.
Anecdotal evidence from companies applying OCP principles has shown 20-30%
faster deployment of new features, highlighting its efficiency in adapting to
changing requirements.
V. Conclusion
Incorporating the Open/Closed Principle into software design not only improves
code quality and robustness but also fosters an environment conducive to
continuous innovation.
1. Base Implementation
class Shape:
def area(self):
raise NotImplementedError("Subclasses must implement this metho
d.")
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
2. Extending Functionality
Now, to add a new shape without modifying the existing code, we simply create a
new subclass for Circle.
import math
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
314CS23078
def area(self):
return math.pi * (self.radius ** 2)
3. Usage
Using these classes, we can calculate the area for various shapes:
shapes = [Rectangle(10, 5), Circle(7)]
314CS23078