Sitemap
Amar Shukla

Amar Shukla

Press enter or click to view image in full size

SOLID Principles

2 min readFeb 13, 2024

--

I’ve planned to write series of articles to explain SOLID principle in easy to understand language with the help of example. All code examples will be in Python3.

The SOLID principles are a set of five design principles in object-oriented programming. These principles collectively provide guidelines for designing software that is easier to understand, maintain and extend over time, leading to more robust and scalable applications. Let’s start with “S” in this article.

Single Responsibility Principle
The Single Responsibility Principle states that a class should have only one reason to change. In other words, a class should have only one responsibility or job.

Get Amar Shukla’s stories in your inbox

Join Medium for free to get updates from this writer.

let’s consider a simplified version of an online food ordering application called “PyFood.” Within this application, we might have classes responsible for managing users, handling orders, and interacting with the restaurant database.

Violation Example

Consider a class called OrderManager that is responsible for both placing orders and sending email notifications to users. This violates Single Responsibility Principle because the class has two distinct responsibilities: order management and email notification.

class OrderManager:
def place_order(self, order):
# Logic to place order
pass

def send_order_confirmation_email(self, user, order):
# Logic to send email notification
pass

To adhere to the principle, we should split the responsibilities into separate classes. Let’s create a new class called EmailSender to handle email notifications.

class EmailSender:
def send_order_confirmation_email(self, user, order):
# Logic to send email notification
pass

class OrderManager:
def place_order(self, order):
# Logic to place order
pass

Now, the OrderManager class is responsible only for managing orders, while the EmailSender class is responsible for sending email notifications. This separation of concerns makes the codebase easier to understand, maintain, and extend.

In the next article, we’ll explore the Open/Closed Principle and demonstrate how to extend the functionality of our application without modifying existing code.

--

--