SRP (Single Responsibility Principle) — Explained with Examples
The Single Responsibility Principle states that a class should have one reason to change, meaning it should handle only one concern or responsibility.
SRP stands for Single Responsibility Principle, the first of the five SOLID principles defined by Robert C. Martin. It states: “A class should have one, and only one, reason to change.”
Why SRP Matters
When a class handles multiple responsibilities, changes to one concern risk breaking unrelated features. The class becomes harder to understand, test, and maintain. By keeping each class focused, you isolate change and reduce ripple effects across the codebase.
Real-World Analogy
A Swiss Army knife does many things but does none of them as well as a dedicated chef’s knife. In the same way, a class that tries to handle data storage, business logic, and UI rendering will be mediocre at all three. Dedicated classes excel at their single job.
Example: Violating SRP
class Invoice:
def __init__(self, customer, total):
self.customer = customer
self.total = total
def calculate_total(self):
# business logic
return self.total * 1.08
def save_to_database(self):
# database logic
print(f"Saving invoice for {self.customer}")
def print_invoice(self):
# presentation logic
print(f"Invoice for {self.customer}: ${self.total}")# Following SRP — three separate classes
class Invoice:
def __init__(self, customer, total):
self.customer = customer
self.total = total
class InvoiceCalculator:
@staticmethod
def calculate(invoice):
return invoice.total * 1.08
class InvoiceRepository:
@staticmethod
def save(invoice):
print(f"Saving invoice for {invoice.customer}")
class InvoicePrinter:
@staticmethod
def print(invoice):
print(f"Invoice for {invoice.customer}: ${invoice.total}")Related Terms
SOLID, Open/Closed Principle, Separation of Concerns, Encapsulation
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro