SOLID & DESIGN PRINCIPLES / OBJECT DESIGN BRIEF

Single Responsibility Principle

The Single Responsibility Principle (SRP) says a class should have only one reason to change.

BeginnerPhase 02 / Topic 1 of 8ResponsibilitiesCollaborationsExtensibility
01

Overview

The Single Responsibility Principle (SRP) says a class should have only one reason to change. A reason to change is a stakeholder or concern: business rules, persistence, formatting, and notification are different concerns.

SRP is not about a class having one method. It is about cohesion: everything in the class should change for the same reason, so a change for one concern cannot accidentally break another.

A restaurant kitchen

The chef cooks, the cashier takes payment, and the server delivers food. If the cashier changes the payment system, the chef's recipes are unaffected. One person doing all three jobs means any change disrupts everything.

02

When to use it

  • A class name includes And or Manager and does many unrelated things.
  • Changing an email template requires editing the same class that calculates invoices.
  • Unit tests need a database, SMTP server, and file system just to test business logic.
  • Different teams frequently edit the same file for unrelated reasons.
03

Where it shows up in interviews

God class refactoring

Recognize it when: Manager/Service class doing everything.

  • Refactor an OrderManager
  • Design an invoice system
Design critique

Recognize it when: 'what is wrong with this class?'

  • Review a UserService that validates, saves, and emails
04

Where it is used in real software

Spring layers

Controllers, services, and repositories each change for different reasons.

Unix tools

Small programs that do one thing well (grep, sort, wc) are SRP at the tool level.

Microservices

Each service owns one business capability, the same principle at system scale.

05

Key terms

Responsibility
A reason to change, tied to one actor or concern.
Cohesion
How closely the members of a class belong together.
Coupling
How much one class depends on others' details.
06

How to apply it

  1. 1
    List the reasons to change

    Ask who would request changes to this class: finance, operations, marketing, the DBA?

  2. 2
    Group members by reason

    Methods and fields that change together stay together.

  3. 3
    Extract each group

    Create focused classes: InvoiceCalculator, InvoiceRepository, InvoiceEmailer.

  4. 4
    Coordinate with a thin service

    A small application service calls each class in order without containing their logic.

07

Splitting an Invoice class

An Invoice class calculates totals, saves to a database, and emails the customer

Step 1 / 4
ResponsibilityChanges whenNew class
Tax and totalsTax rules changeInvoiceCalculator
PersistenceDatabase or schema changesInvoiceRepository
EmailTemplate or provider changesInvoiceNotifier
OrchestrationWorkflow order changesInvoiceService

NOWResponsibility: Tax and totals | Changes when: Tax rules change | New class: InvoiceCalculator

Each class can now be tested alone. Swapping the email provider touches only InvoiceNotifier.

08

Implementation

// Three reasons to change in one class.class Invoice {  constructor(public items: LineItem[], public customerEmail: string) {}   total(): number {    const subtotal = this.items.reduce((sum, item) => sum + item.price * item.qty, 0);    return subtotal * 1.18; // tax rule  }   save(): void {    db.query("INSERT INTO invoices ...", [this.total()]); // persistence  }   email(): void {    smtp.send(this.customerEmail, `Your total is ${this.total()}`); // notification  }}
09

Complexity and performance

Classesmore, smaller

Each focused on one concern.

Test setupsimpler

Pure logic tests need no infrastructure.

10

Trade-offs

Over-splitting

Splitting every method into its own class scatters logic and hurts readability. Split along real change boundaries, not line counts.

Indirection

More classes mean more files to navigate. Good names and a thin orchestrating service keep the flow readable.

11

Variants and related techniques

SRP at module level

The same idea applies to packages and services: a service should own one business capability.

Separation of concerns

SRP is SoC applied to classes.

12

Common mistakes

  • Interpreting SRP as one method per class.

    Fix: Focus on one reason to change, which can involve many methods.

  • God classes named Manager, Helper, or Utils.

    Fix: Name classes after one responsibility; vague names signal mixed concerns.

13

Interview questions

How do you identify SRP violations?

Ask how many different actors could request a change to the class. If finance and marketing both edit it, it has at least two responsibilities.

Does SRP increase the number of classes?

Yes, but each is smaller, easier to test, and safer to change. The goal is lower risk per change, not fewer files.

14

Practice problems

ProblemDifficultyWhat it trains
Refactor a UserManagerEasySplit validation, persistence, and email.
Report generatorMediumSeparate data fetching, formatting, and export.