← Back to Roadmap

Single Responsibility Principle (SRP)

Medium

In plain terms

The Single Responsibility Principle says that a class should have only one job—one reason to change. If your class does user validation, sends emails, and updates the database, three different changes (validation rules, email format, DB schema) could force you to touch the same class. That makes it fragile and hard to test.

Split such a class into smaller ones: UserValidator, EmailSender, UserRepository. Each has one reason to change. SRP is the foundation of the other SOLID principles; small, focused classes are easier to extend and reuse.

What you need to know

  • One reason to change per class
  • Split large classes into focused ones
  • Easier to test and change

Example

Code is language-agnostic in spirit; adapt the idea to your language:

// Bad: one class, many jobs
// class User { validate(); sendEmail(); saveToDb(); }

// Good: one job each
class UserValidator {
  validate(user) { /* ... */ }
}
class EmailService {
  send(to, body) { /* ... */ }
}
class UserRepository {
  save(user) { /* ... */ }
}

Why this matters

SRP is the most frequently cited SOLID principle. Interviewers ask for examples of violating it and how you would refactor.

How it connects

SRP is the basis for the others: small, focused classes make OCP and DIP easier. It connects to "functions do one thing" from programming basics and to testability (one responsibility = easier to mock and test).

Interview focus

Be ready to explain these; they come up often.

  • "A class should have only one reason to change." Give an example of a class with multiple reasons.
  • How to fix: split into smaller classes (e.g. validation, persistence, notification separate).
  • Benefit: changes are localized; testing and reuse are simpler.

Learn more

Dive deeper with these resources: