Single Responsibility Principle (SRP)
h2>Definition
A class should have only one responsibility or one reason to change.
👉 One class = One job.
Purpose
- Keep classes focused
- Reduce complexity
- Improve maintainability
- Make code easier to test
- Avoid tightly coupled logic
Bad Example ❌
public class InvoiceService
{
public void CreateInvoice()
{
Console.WriteLine("Invoice Created");
}
public void SaveToDatabase()
{
Console.WriteLine("Saved to DB");
}
public void SendEmail()
{
Console.WriteLine("Email Sent");
}
}
Problem
This class handles:
- Invoice creation
- Database operations
- Email sending
👉 Multiple responsibilities.
Good Example ✅
Invoice Logic
public class InvoiceService
{
public void CreateInvoice()
{
Console.WriteLine("Invoice Created");
}
}
Database Logic
public class InvoiceRepository
{
public void Save()
{
Console.WriteLine("Saved to DB");
}
}
Email Logic
public class EmailService
{
public void Send()
{
Console.WriteLine("Email Sent");
}
}
Key Concept
Instead of:
One class doing everything
We do:
Separate focused classes
👉 Easier to manage and extend.
Real-Time Scenario
Invoice System:
- InvoiceService → invoice logic
- InvoiceRepository → database logic
- EmailService → notifications
👉 Each class has single responsibility.
Advantages
- ✔ Easier maintenance
- ✔ Better readability
- ✔ Easier unit testing
- ✔ Reduced side effects
- ✔ Better scalability
Disadvantages
- ✖ More classes/files
- ✖ Slightly increased structure complexity
When to Use
Use SRP when:
- Class has multiple responsibilities
- Business logic becomes large
- Different changes happen frequently
- Code becomes difficult to maintain
Real Project Mapping (.NET + Angular)
| Layer | Responsibility |
|---|---|
| Controller | Handle HTTP requests |
| Service | Business logic |
| Repository | Database operations |
| EmailService | Notifications |
| LoggerService | Logging |
ASP.NET Core Real Example
Controller → Request Handling
Service → Business Logic
Repository → Data Access
👉 SRP everywhere in Clean Architecture.
SRP vs Separation of Concerns
| SRP | Separation of Concerns |
|---|---|
| Class-level principle | System-level principle |
| One class = one job | Divide application into sections |
Pro Tip
SRP works best with:
- Clean Architecture
- Repository Pattern
- Dependency Injection
- Microservices
Summary
SRP helps you:
- Keep classes focused
- Reduce complexity
- Improve maintainability
👉 Perfect for:
- Enterprise applications
- APIs
- Microservices
- Large-scale projects
Comments
Post a Comment