Design Patterns – Is the Single Responsibility Principle Applicable to Functions?

design-patternssingle-responsibility

According to Robert C. Martin, the SRP states that:

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

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 states:

There are several problems with this function. First, it’s large, and when new employee types are added, it will grow. Second, it very 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. [emphasis mine]

Firstly, I thought the SRP was defined for classes, but it turns out it's also applicable to functions. Secondly, how is that this function has more than one reason to change? I can only see it changing because of a change on Employee.

Best Answer

One often missed detail of the Single Responsibility Principle is that the "reasons for change" are grouped by use-case actors (you can see a full explanation here).

So, in your example, the calculatePay method will need to be changed whenever new types of Employees are required. Since one type of employee may have nothing to do with another, it would be a violation of the principle if you keep them together, since the change would affect different user-groups (or use-case actors) in the system.

Now, about whether the principle applies to functions: Even if you have a violation in only one method, you are still changing a class for more than one reason, so it is still a violation of SRP.