Single Responsibility Principle (SRP) is one of the core principles of object-oriented design, part of the SOLID principles.
The main idea is that a class should have only one responsibility, meaning it should do only one thing, and that responsibility should be fully encapsulated within the class.
Why is SRP important?
- Easier to maintain: If a class has multiple responsibilities, changing one part might unintentionally affect the others. Breaking down responsibilities minimizes such risks.
- Better scalability: A class with a clear role is easier to extend or refactor.
- Improved testability: Smaller, focused classes are easier to test.
Example in Python
Let’s imagine a library system for managing books. Without applying SRP, we might create a class that does too much:
Bad Example:
class LibraryManager: def add_book(self, book): # Add a book to the database pass def remove_book(self, book_id): # Remove a book from the database pass def generate_report(self): # Generate a report of books pass
This class has multiple responsibilities:
- Managing books (adding and removing them).
- Generating reports.
If the way books are stored in the database changes, this class might need updates, which could inadvertently affect the report generation functionality.
Better Example (Using SRP):
class BookDatabase: def add_book(self, book): # Add a book to the database pass def remove_book(self, book_id): # Remove a book from the database pass class ReportGenerator: def generate_report(self, books): # Generate a report of books pass
Now, each class has a single responsibility:
BookDatabase
handles book storage operations.ReportGenerator
is solely responsible for generating reports.
db = BookDatabase() report_gen = ReportGenerator() # Add a book db.add_book({"title": "1984", "author": "George Orwell"}) # Generate a report books = [{"title": "1984", "author": "George Orwell"}] report_gen.generate_report(books)
This approach results in a more modular, maintainable, and scalable codebase.