Cover Image

Single Responsibility Principle

SRP

“A class should have one, and only one, reason to change.” – Robert C. Martin

The Single Responsibility Principle (SRP) states that a class or module should be responsible for only one part of the software’s functionality, and that responsibility should be entirely encapsulated by the class.

When to use

Apply SRP whenever you write a class or function. If it does “this” AND “that”, it typically violates SRP.

Why it matters

  • Maintainability: Changes to one part of the system (e.g., database logic) don’t break unrelated parts (e.g., UI rendering).
  • Testability: Smaller, focused classes are easier to test in isolation.
  • Reusability: Decoupled responsibilities can be reused in different contexts without carrying unnecessary baggage.

Signs of Violation

  • The class has many instance variables.
  • The class mentions different layers (e.g., SQL and HTML) in the same file.
  • You have to change the class for different business reasons (e.g., “change report format” AND “change calculation logic”).
  • The class name is generic like Manager, Processor, or System.

Explanation

Problem

“God classes” that know too much and do too much are hard to understand, hard to maintain, and hard to test. A change in one area (like how data is saved) might inadvertently break another area (like how data is verified) if they are tangled in the same class.

Solution

Split the large class into smaller classes, each handling a single specific responsibility.

Real world analogy

In a restaurant, the chef cooks, the waiter serves, and the janitor cleans. If the chef had to stop cooking to clean the tables, the kitchen would stop, and customers would wait. Specialization allows for efficiency and isolation of issues.

Pros and Cons

Pros Cons
  • High cohesion
  • Low coupling
  • Easier debugging
  • More classes/files to manage
  • Code might feel more fragmented potentially
  • Comparison

    • Interface Segregation Principle (ISP): SRP deals with the internal responsibility of a class, whereas ISP deals with the public interface presented to clients.

    Code example

    Typescript

    Bad (Violation)

    Good (Adherence)

    PHP

    Bad (Violation)

    Good (Adherence)