SOLID PrinciplesSingle Responsibility PrincipleMedium⏱️ ~3 min

SRP Violation Structure: Identifying Mixed Responsibilities

Anatomy of an SRP Violation

SRP violations occur when a class mixes concerns from different actors or business domains. The key indicator is asking: "If requirement X changes, would this class need to be modified? What about requirement Y from a different department?" If multiple unrelated requirements affect the same class, SRP is violated.

Classic Violation Example: Invoice Processing

Before (Violation)
Invoice
- items: List
- customer: Customer
+ calculateTotal(): Money
+ saveToDatabase(): void
+ generatePDF(): File
+ sendEmail(): void
Handles business logic, persistence, reporting, and notifications
After (SRP Applied)
Invoice
+ calculateTotal(): Money
InvoiceRepository
+ save(Invoice): void
InvoiceFormatter
+ generatePDF(Invoice): File
NotificationService
+ sendInvoice(Invoice): void
Each class has one reason to change

Identifying the Actors

The violated Invoice class serves four different actors:

First, the Finance team owns business logic like tax calculations and discounts. They change calculateTotal() when tax rates change.

Second, the Database team owns persistence strategy. They change saveToDatabase() when migrating from SQL to NoSQL.

Third, the Reporting team owns output formats. They change generatePDF() when adding watermarks or changing layouts.

Fourth, the Customer Success team owns notification templates. They change sendEmail() when updating branding or adding SMS support.

Consequences of Violation

When the Reporting team updates PDF generation to fix a margin issue, they must modify the Invoice class. This requires recompiling and retesting all invoice functionality, including database operations and email sending. If the reporting developer introduces a bug, it might break invoice persistence. Changes ripple across unrelated concerns.

Interview Tip: In interviews, identify SRP violations by listing "who might ask for changes." If different departments or roles would request changes to the same class, it is a violation.

Refactoring Strategy

To fix SRP violations, extract each responsibility into its own class. The original class becomes a coordinator or facade if needed, but core responsibilities live in focused, single-purpose classes. Use dependency injection to wire these classes together at runtime.

💡 Key Takeaways
SRP violations happen when one class serves multiple actors or business concerns
Each responsibility should answer to only one stakeholder or department
Refactoring involves extracting each concern into a dedicated class
The test is: 'How many different reasons would cause this class to change?'
📌 Examples
1Invoice class handling calculation, persistence, formatting, and notifications
2Employee class managing payroll, HR records, and timesheet reporting
← Back to Single Responsibility Principle Overview