🔍

Understanding the Single Responsibility Principle

Sep 4, 2024

Single Responsibility Principle (SRP)

Introduction

  • Discusses one of the SOLID principles: Single Responsibility Principle (SRP)
  • Common misinterpretations of SRP

Definition of SRP

  • Core Definition:
    • A module (class, function, or package) should have only one responsibility or reason to change.
  • A module should only be modified by one actor (stakeholder).

Clarification of Terms

  • Module:
    • A set of functions, a class, or a package.
  • Actor:
    • A stakeholder requesting changes to the module.

Example: Employee Class

  • Class Structure: Employee class with methods:
    • calculate_salary() - Used by CFO
    • calculate_hours() - Used by HR
    • save_employee_data() - Used by Technical/Engineering department

Problem with Current Design

  • All methods in one class lead to dependencies.
  • Changes by one actor can inadvertently affect the functionality needed by another actor, breaking SRP.

Correcting the Design

  • Solution: Decompose the Class
    • Create separate classes:
      • SalaryCalculator
      • HoursCalculator
      • EmployeeStore
    • Each class handles its own responsibility, preventing changes from impacting unrelated functionalities.

Example: Restaurant Bill Class

  • Class Structure:
    • MenuItem class with properties (e.g., item name, tax, discount)
    • Bill class with methods for:
      • Calculating the total amount
      • Printing the bill
      • Saving the bill to a database

Problem with Bill Class Design

  • Multiple responsibilities can lead to changes in one area affecting the entire class.
  • Example of changing the database implementation affecting the Bill class.

Correcting Bill Class Design

  • Solution: Further Decomposition
    • Create separate classes:
      • BillCalculator - calculates the final amount
      • BillPrinter - handles printing
      • BillStore - manages data storage
  • Keeping each responsibility separate ensures that changes in one area do not affect others.

Conclusion

  • Important Note:
    • SRP does not mean one class should have only one public method; it means that changes should be driven by one actor/group.
  • Design Philosophy:
    • Design is subjective; focus on fulfilling business requirements and ease of change.
  • Consider potential class proliferation and balance it with practicality based on business needs.

Additional Resources

  • References to further reading including Uncle Bob's book "Clean Code".

Next Topic

  • Upcoming discussion on the next SOLID principle: Open/Closed Principle.