What is the Single Responsibility Principle, with an example?
Quick Answer
A class should have one responsibility — one reason to change. If a class does data access and business rules and report formatting, a change to any one of those forces you to touch (and retest) code that has nothing to do with your change.
Single Responsibility says a class should have one reason to change. The example I use is an invoice class that loads data from the database, calculates tax, renders a PDF and emails it — that's four separate concerns, so a change to the PDF layout means editing and retesting a class that also owns tax logic. I'd pull those apart into a repository, a tax calculator, a renderer and an email sender, with a small service tying them together. The caveat is not to over-split — if two things always change at the same time, keeping them together is more cohesive.
“Reason to change” usually maps to an actor or a concern: persistence, business policy, presentation, notification. A common violation:
InvoiceManagerthat queries the database, calculates tax, generates a PDF and sends an email. Four reasons to change, four teams potentially involved.
Refactor into InvoiceRepository, TaxCalculator, InvoicePdfRenderer, EmailSender, coordinated by a thin service. Benefits: each is small, independently testable, and reusable. The risk is over-splitting — SRP is about cohesion, not line count. If two things always change together, they probably belong together.