Is the principle of single responsibility applicable to functions?

According to Robert C. Martin, SRP states that:

There should never be more than one reason for changing a class.

However, in his book Clean Code, Chapter 3: Functions, he shows the following block of code:

public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateHourlyPay(e); case SALARIED: return calculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); } } 

And then it says:

There are several problems with this feature. Firstly, its large, and when new types of employees are added, it will grow. Secondly, it very clearly does more than one. Third, it violates the principle of single responsibility (SRP), because there are several reasons for changing it . [emphasis mine]

First, I thought SRP was defined for classes, but it turns out that it also applies to functions. Secondly, how does this function have more than one reason for change? I can see how this changes due to changes in Employee.

+6
source share
1 answer

You can think of the method above as an object belonging to the following class:

 class PaymentCalculator implements Function<Employee, Money> { Money apply(Employee) { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateHourlyPay(e); case SALARIED: return calculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); } } } 

Then try to find the reasons why this class can be changed:

  • changes in employee wages
  • changes in the logic of calculations (new parameters like employee position, experience, etc.)

For at least these two types of changes, you will have to make corrections to this method. It is worth noting that the goal of SRP is to achieve low traction and a high degree of traction. To understand the benefits of this, try to imagine that you have a large system with hundreds of classes and methods like this: calculatePay, calculateVacation, createDepartment, etc. And all these classes and methods have such code. Will it be easy to make changes?

PS After you see the long if-else or case arguments, you can start thinking about SRP.

+1
source

Source: https://habr.com/ru/post/983506/


All Articles