Graduate Program KB

Chapter 7 - The Single Responsibility Principle

  • Had different versions described:
    • A module should have one, and only one, reason to change
    • A module should be responsibile to one, and only one, user or stakeholder
    • A module should be responsible to one, and only one, actor
  • Module is a cohesive set of functions and data structures

Symptom 1. Accidental Duplication

  • Employee Class
    • calculatePay
    • reportHours
    • save
  • These 3 methods are used by 3 different actors
    1. CFO, calculatePay
    2. COO, reportHours
    3. CTO, save
  • All 3 actors are coupled together, actions of any actor can affect another actor
  • Example:
    • calculatePay and reportHours both share a function called regularHours
    • CFO team uses calculatePay and COO uses reportHours
    • A developer tasked with updating calculatePay for CFO team sees the function regularHours, think its ok to change this function.
    • The developer made the changes and fully tested it, and it works as desired according to the CFO team
    • However, it has not been tested with the COO team, and now it is working incorrectly for the COO team
  • Problem occurs because code for different actors are placed together, better to seperate code for different actors

Symptom 2. Merges

  • 2 different teams working on the same files will have merge conflicts
  • In this case, CTO and COO both work on the Employee class, their changes will collide
  • Can be avoided if you seperate code for different actors

Solutions

  • Many different solutions:
    • Create 3 different classes, for each method
      • PayCalculator, calculatePay
      • HourReporter, reportHours
      • EmployeeSave, saveEmployee
    • Issue with this, is there are 3 extra classes to create instances of and track
    • Can be solved using the Facade pattern
    • The Facade class contains little code and is only used to instantiate and delegate objects to the classes with the functions
    • Could also use the Employee class to keep the most important method and use that class as the facade for the low level functions

Conclusion

  • SRP is about functions and classes but also has different forms at 2 levels
  • Components Level: Common Closure Principle
  • Architectural Level: Axis of Change