DEV Community

Cover image for Single Responsibility Principle
Jorjis Hasan
Jorjis Hasan

Posted on

Single Responsibility Principle

Scene-0: In a restaurant customer orders meatballs. Chef Carlos chopped and baked the meat, onward that he fried the meat and served that.

Scene-1: Likewise, the same customer orders meatballs again, and this time, Chef Carlos chops the meat, Chef Steve bakes and fries, and waiter Alex serves the dish.

Considering these two scenarios, scene-1 has much better work efficiency than scene-0. This scene-1 is optimized by following SRP principle. It has three people for different tasks to be the work done.


SRP, aka single-responsibility-principle dictates that a class should have a single responsibility, ensuring modular and maintainable software design.

1. FileHandler Class:

class FileHandler:
    def read_file(self, filename):  # Responsibility: File reading
        # Code to read file content

    def write_file(self, filename, content):  # Responsibility: File writing
        # Code to write content to a file

Enter fullscreen mode Exit fullscreen mode

2. Employee Class:

class Employee:
    def calculate_salary(self):  # Responsibility: Salary calculation
        # Code to calculate salary

    def generate_pay_slip(self):  # Responsibility: Pay slip generation
        # Code to generate pay slip

Enter fullscreen mode Exit fullscreen mode

Each class has a clear and distinct responsibility in these examples, adhering to the Single Responsibility Principle. The FileHandler class focuses on file-related operations, while the Employee class has separate methods for salary calculation and pay slip generation.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay