Video in progress

How do you recognize a class that violates the Single Responsibility principle?

If a class has several independent reasons to change (say, a business rule, a database format and an email template all in one class), SRP is violated. Signs: a very long class, "Manager"/"Util" in the name, imports from different areas.

📖 Answer

Here is a typical example:

public class InvoiceService {
    public long calculateTotal(Invoice inv) { ... }      // business rule
    public void saveToDb(Invoice inv) { ... }            // JDBC, SQL
    public byte[] toPdf(Invoice inv) { ... }             // PDF library
    public void emailToCustomer(Invoice inv) { ... }     // SMTP
}

Four different people would ask for changes to this class: the accountant (the tax formula), the DBA (a table changed), the designer (how the PDF looks) and the infrastructure team (another service instead of SMTP). Every change risks breaking the other parts.

The split version:

  • InvoiceCalculator for the calculation;
  • InvoiceRepository for storage;
  • InvoicePdfRenderer for the PDF;
  • InvoiceMailer for sending.

I check myself with these questions:

  • can you describe the class in one sentence without the word "and"?
  • how many things do you have to mock to write a unit test? If more than five, be suspicious;
  • does the class change often in git history for different kinds of reasons?

SRP doesn't mean "one method per class". It is about responsibility, not about the number of methods.