Skip to main content

Single Responsibility Principle (SRP)

“A class should have only one reason to change.” In other words, each class or module should focus on a single responsibility or functionality.

Purpose

  • Ensures high cohesion by keeping classes focused on one task or role.
  • Makes code easier to maintain and less prone to bugs – a change affecting one responsibility won’t unexpectedly impact others.
  • Simplifies testing, since each class has a small, well-defined behavior to verify.

Minimal Example

Below, TextManager violates SRP by handling both text processing and file saving. We then refactor into two classes (TextProcessor and TextFileSaver), each with a single responsibility (one for text manipulation, one for persistence).

More Realistic Example

Consider a user account system. Originally, a UserManager class might both create users and send welcome emails – two separate responsibilities. Applying SRP, we separate these concerns into a UserManager (handles user creation logic) and an EmailService (handles email sending). The UserManager uses EmailService for notifications, but its own responsibility is limited to user-related operations.