LogRocket Blog

Solid series: Single Responsibility Principle (SRP)

thumbnail
  • SRP (Single Responsibility Principle):
    • Definition: SRP is the first letter of the SOLID design principles, which stands for Single Responsibility Principle.
    • Concrete aspects of a system: Responsibilities in a system such as authentication and data management should be separated into different classes.
  • Example of an SRP violation:
    • A class in TypeScript that combines database operations, authentication, and sending emails violates the SRP.
  • Refactoring to follow SRP:
    • Separate concerns into different classes like DatabaseOperations, Authentication, and EmailSender classes to adhere to SRP.
  • Detecting SRP violations:
    • Class changes for multiple reasons and too many dependencies in a class can indicate SRP violations.
  • Code implementation of SRP:
    • Python, Java, TypeScript, and C# examples of using well-structured classes to follow SRP.
  • Benefits of SRP:
    • SRP ensures high-quality code by enforcing classes to have a single responsibility.
  • Common misconceptions of SRP:
    • Too much abstraction and misunderstanding of the principle can lead to misconceptions.
  • SRP in modular monolithic architecture:
    • Each module focuses on a specific function, maintaining modularity and clarity in code structure.
  • SRP in microservices architecture:
    • Each microservice handles a specific business capability, enabling independent deployment and scalability.