The Single Responsibility Principle says a module should have one reason to change. It does not mean every class must contain one method; unrelated policies should not be coupled.
Example:
public sealed class InvoiceService(
IInvoiceRepository repository,
IInvoiceRenderer renderer,
IEmailSender email)
{
public async Task SendAsync(Guid id, CancellationToken ct)
{
var invoice = await repository.GetAsync(id, ct);
var document = renderer.Render(invoice);
await email.SendAsync(invoice.CustomerEmail, document, ct);
}
}
Persistence, rendering, and transport can change independently. Do not split cohesive domain rules into tiny classes mechanically; the goal is safer change, not maximum file count.
Backbencher Developer · · 0 likes
I will explain the Single Responsibility Principle (SRP), the "S" in SOLID: a class should have only one reason to change — it should be responsible to one actor or one concern.
Violation example
public class InvoiceService
{
public decimal CalculateTotal(Invoice i) { /* tax and discount rules */ }
public void SaveToDatabase(Invoice i) { /* SQL code */ }
public string GeneratePdf(Invoice i) { /* PDF layout */ }
public void EmailCustomer(Invoice i) { /* SMTP code */ }
}
This class changes when tax rules change (finance), when the database schema changes (DBA), when the PDF design changes (marketing) and when the email provider changes (operations). Each change risks breaking unrelated features, and testing the tax logic requires dealing with SQL and SMTP.
Applying SRP
public class InvoiceCalculator { public decimal Total(Invoice i) { ... } }
public class InvoiceRepository(AppDbContext db) { public Task SaveAsync(Invoice i) { ... } }
public class InvoicePdfRenderer { public byte[] Render(Invoice i) { ... } }
public class InvoiceMailer(IEmailSender sender) { public Task SendAsync(Invoice i, byte[] pdf) { ... } }
public class InvoiceWorkflow(InvoiceCalculator calc, InvoiceRepository repo, InvoicePdfRenderer pdf, InvoiceMailer mail)
{
public async Task CompleteAsync(Invoice invoice)
{
invoice.Total = calc.Total(invoice);
await repo.SaveAsync(invoice);
await mail.SendAsync(invoice, pdf.Render(invoice));
}
}
Benefits
- Each class is small, easier to understand and to unit test (the calculator needs no database).
- Changes are isolated: a new PDF layout touches only the renderer.
- Team members can work in parallel with fewer merge conflicts.
- Classes become reusable (the renderer can be used for invoice previews).
Practical balance
SRP does not mean "one method per class". Group code that changes together for the same reason. Over-splitting creates many tiny classes and indirection. Signs you need SRP: a class name with "And" or "Manager", very long files, many unrelated dependencies in the constructor, or frequent changes for different reasons.
The other principles, briefly: Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.