Understanding the Single Responsibility Principle

后端 未结 2 1324
闹比i
闹比i 2020-12-17 20:25

I am quite confused on how to determine if a single method has one responsibility being done just like the following code from the book Clean Code

public Mon         


        
相关标签:
2条回答
  • 2020-12-17 21:02

    I generally apply the SRP at the class level. It prevents classes becoming too big and taking on too many roles.

    I treat the 'responsibilities' as conceptual. Therefore, I would argue that your method has only one responsibility: to calculate pay.

    I try and follow Google's guidelines on this and look for these warning signs that suggest you're wandering away from the SRP:

    • Summarising what the class does includes the word ‘and’.
    • Class would be challenging for new team members or inexperienced developers to read and quickly ‘get it’.
    • Class has fields that are only used in some methods.
    • Class has static methods that only operate on parameters.

    On another note, however, your code contains a switch statement that suggests you might be wandering away from the OCP...

    0 讨论(0)
  • 2020-12-17 21:08

    "...clearly does more than one thing. Third, it violates the Single Responsibility Principle (SRP) because there is more than one reason for it to change."

    There lies your answer. Every time a new Employee.Type is added that method will have to change. Also, the calculation for each Employee.Type might change too.

    A better solution would be to create an Abstract Factory for Employee and each derivative of Employee having it's own implementation of CalculatePay. This way, only ONE class needs to changed when the Calculation changes or when a new Employee.Type is added.

    Here is another extract from Clean Code that explains in more detail -

    The solution to this problem (see Listing 3-5) is to bury the switch statement in the basement of an ABSTRACT FACTORY,9 and never let anyone see it. The factory will use the switch statement to create appropriate instances of the derivatives of Employee, and the various functions, such as calculatePay, isPayday, and deliverPay, will be dispatched polymorphically through the Employee interface. My general rule for switch statements is that they can be tolerated if they appear only once, are used to create polymorphic objects

    0 讨论(0)
提交回复
热议问题