Sunday, April 24, 2016

Switch Statement

It shows just one of the operations that might depend on the type of employee.

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.
Fourth, it violates the Open Closed Principle (OCP) because it must change whenever new types are added.

But possibly the worst problem with this function is that there are an unlimited number of other functions that will have the same structure.
For example we could have:
  • isPayday(Employee e);
  • deliverPay(Employee e, Money pay);

The solution to this problem is to bury the switch statement in the basement of an abstract factory, and never let anyone see it.

The factory will use the switch statement to create appropriate instance of the derivatives of employee, and the various functions, such as calculatePay, isPayday and deliverPay will be dispatched polymorphically through the employee interface.