Home and Living Room

Gazette

open closed principle example python

Open Closed Principle Python: Easy Example & Best Practices

By David Harris
AD

In Python, the open closed principle serves as a foundational guideline for writing maintainable and extensible code. It dictates that software entities such as classes, modules, or functions should be open for extension but closed for modification. This means you can introduce new functionality without altering the existing, tested code, thereby minimizing the risk of introducing bugs.

Understanding the Core Concept

The primary goal of this principle is to protect your existing code from the ripple effects of change. When requirements evolve—and they inevitably do—you should be able to add new behavior by creating new classes or functions, rather than rewriting the logic that already works. In Python, this is often achieved through polymorphism, inheritance, or dependency injection, where abstract interfaces define a contract that concrete implementations fulfill.

The Role of Abstract Base Classes

Abstract Base Classes (ABCs) provide a robust way to define the open closed principle example python structure. By defining an interface with `@abstractmethod`, you ensure that any new payment processor adheres to a consistent structure. This allows the core billing logic to remain untouched regardless of how many payment methods you add.

AD
Wrting Scalable Data Science Code with the Open-Closed Principle
Wrting Scalable Data Science Code with the Open-Closed Principle
a poster with different types of python functions
a poster with different types of python functions
a screen shot of a web page with the text python if - else inside print
a screen shot of a web page with the text python if - else inside print

Practical Implementation Example

Consider a system that processes different types of notifications. Instead of writing a monolithic function that uses conditional logic to decide how to send an email, SMS, or push notification, you can rely on polymorphism. Each notification type is a separate class, and the sender interacts with a common interface.

Step-by-Step Code Illustration

Here is a detailed example demonstrating the open closed principle example python in action. The `NotificationSender` class depends on an abstract `Notification` interface. Adding a new `FaxNotification` type requires zero changes to the sender logic.

Python Conditional Statements & Loops
Python Conditional Statements & Loops
three different types of python programming
three different types of python programming
Python Notes
Python Notes
Python
from abc import ABC, abstractmethod

# Abstract Interface (Closed for modification, Open for extension)
class Notification(ABC):
    @abstractmethod
    def send(self, message: str):
        pass

# Concrete Implementations
class EmailNotification(Notification):
    def send(self, message: str):
        print(f"Sending Email: {message}")

class SMSNotification(Notification):
    def send(self, message: str):
        print(f"Sending SMS: {message}")

# Context that relies on the abstraction
class NotificationSender:
    def __init__(self, notification: Notification):
        self._notification = notification

    def dispatch(self, message: str):
        self._notification.send(message)

# Usage
if __name__ == "__main__":
    email_sender = NotificationSender(EmailNotification())
    email_sender.dispatch("Hello via Email!")

    sms_sender = NotificationSender(SMSNotification())
    sms_sender.dispatch("Hello via SMS!")

Benefits in Real-World Applications

By adhering to this principle, teams can scale their applications without facing exponential complexity. In a large codebase, modifying a core function that handles multiple responsibilities is dangerous. However, extending the system by introducing new classes that inherit from a base is safe and predictable. This leads to a more robust architecture where new features integrate seamlessly.

Decoupling and Testability

Writing code that is closed for modification promotes decoupling. Components interact through well-defined contracts rather than concrete implementations. This decoupling makes unit testing significantly easier. You can mock the abstract interface to test the `NotificationSender` logic in isolation, verifying that it calls the `send` method correctly without needing a live email server or SMS gateway.

AD

Common Pitfalls and Misconceptions

A frequent mistake is over-engineering. Applying the open closed principle rigorously to every tiny change can lead to an explosion of micro-classes, making the code hard to navigate. The key is to apply it where change is most likely—typically at points of variation, such as payment gateways, data export formats, or plug-in architectures. The principle is a tool for managing complexity, not a dogmatic rule to be applied everywhere.

an object is a class instante that allows programming to use variablely and method
an object is a class instante that allows programming to use variablely and method
an open function in python is used to open a file for reading, writing, or appending
an open function in python is used to open a file for reading, writing, or appending
Beautiful Graphic with Python Turtle 🔥✨
Beautiful Graphic with Python Turtle 🔥✨
OOPs in Python
OOPs in Python
Data Science Techniques, Programming Terminology Guide, Basic Python Dictionary Tutorial, How To Iterate Over A Dictionary In Python, Programming Language Terms, Python Dictionary Keys And Values, How To Create A Nested Dictionary In Python, How To Make A Nested Dictionary In Python, How To Sort Dictionary By Key In Python
Data Science Techniques, Programming Terminology Guide, Basic Python Dictionary Tutorial, How To Iterate Over A Dictionary In Python, Programming Language Terms, Python Dictionary Keys And Values, How To Create A Nested Dictionary In Python, How To Make A Nested Dictionary In Python, How To Sort Dictionary By Key In Python
a poster with the words python programming written in different languages and numbers, on top of it
a poster with the words python programming written in different languages and numbers, on top of it
10 Python Tricks Every Beginner Should Know
10 Python Tricks Every Beginner Should Know
a poster with the words python file handling and other things to do in this text box
a poster with the words python file handling and other things to do in this text box
Python while Loops: Repeating Tasks Conditionally – Real Python
Python while Loops: Repeating Tasks Conditionally – Real Python
python Loops for loop and while loop
python Loops for loop and while loop
visit site for learning loops in python
visit site for learning loops in python
a screenshot of a computer screen with the text loop while empython
a screenshot of a computer screen with the text loop while empython
Python reflection inspect and introspect #programming #tutorial
Python reflection inspect and introspect #programming #tutorial
the top 10 python tricks every beginer should know
the top 10 python tricks every beginer should know
an info poster showing the different types of computers and how they use them to work
an info poster showing the different types of computers and how they use them to work
two screens showing the same programming program as well as an image of numbers and symbols
two screens showing the same programming program as well as an image of numbers and symbols
the top 60 python project ideas
the top 60 python project ideas
Python tip
Python tip
Python Requests Library: GET, POST & DELETE Examples | API Cheat Sheet
Python Requests Library: GET, POST & DELETE Examples | API Cheat Sheet
AD