Interview ReadyLesson 1 of 5 in SOLID PrinciplesFree preview

Single Responsibility

Single Responsibility Principle (SRP): a class should have one reason to change. "Reason to change" means one group of people or one concern that can ask for a change.

class Invoice {
    double total() { ... }          // business rules (finance team)
    void print() { ... }            // formatting (UI team)
    void saveToDb() { ... }         // storage (DB team)
}

Three different concerns live in one class. A change to the PDF layout forces you to edit and retest the class that also does tax maths. Split it:

class Invoice { double total() { ... } }
class InvoicePrinter { void print(Invoice i) { ... } }
class InvoiceRepository { void save(Invoice i) { ... } }

Each class is now small, easy to test, and changes for one reason only.

The trap: SRP does not mean "one method per class". A class can have many methods, as long as they all serve the same concern.

In interviews: you may be shown a "God class" (a UserManager that validates, emails, logs and saves) and asked how you would split it. Name the separate concerns, then give each its own class.

Practice

Solve 3 of 3 to complete this lesson.

0/3 solved

Solve 3 more to complete this lesson, or move on and come back later.

Skip to next: Open Closed