Skip to main content

What does the Single Responsibility Principle mean?

The Single Responsibility Principle (SRP) means that a class, module, or function should have only one reason to change.

In detail:

1. The essence of SRP

Each component of a system should be responsible for one logically cohesive task. If a class ends up with more than one responsibility, it becomes more complex, less predictable, and harder to test.

2. Reason to change

By "a single reason to change" we mean that if two different aspects of logic force you to rewrite the same class, it has two responsibilities. For example: a change in business logic and a change in the logging format are different reasons.

3. Why this matters

  • It simplifies code maintenance, because a change in one part does not break another.
  • It makes code easier to test - a component focuses on one behavior.
  • It reduces coupling - changes in business rules do not require rewriting infrastructure code.

4. Example of an SRP violation

A UserService class that simultaneously:

  • creates a user,
  • sends an email notification,
  • writes a log entry. These responsibilities belong to different domains: business logic, communication, logging.

5. What correct looks like

Instead of one "big" class:

  • UserCreator - responsible only for creating a user,
  • EmailNotifier - only for sending emails,
  • Logger - only for logging. Then, changing the email template, for example, does not affect user creation in any way.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.