TDD: Refactoring with Polymorphism

Please see my other Test Driven Development articles.

Using polymorphism to refactor SRP violations.

Single Responsibility Principle (SRP) violations are one of the most common issues found in code.
Either the class or its behavior is attempting to fulfill more than one primary purpose.
In this example, I will illustrate how polymorphism provides a powerful method to refactor violations of SRP.

I will began with an example application that manages employee payroll.
Each of the three types of employees need their payroll managed, yet each has slightly different needs with regards to the amount of reimbursement.


2-tdd-refactoring-with-polymorphism 3-tdd-refactoring-with-polymorphism

As you can see, each employee type’s method for retrieving payroll which presents a challenge to the CompanyPayroll class in determining which type each object represents as well as which behavior should be used for each object.


In order to overcome this challange and protect the API from potential changes in the future to the algorithm which determines payroll for each employee, I will implement a contract in the form of an interface for each employee object to adhere to in order to call the payroll methods.


I will then implement that interface unto each employee type class so that I have a single point of maintenance in the future when utilizing the necessary behavior to determine payroll.


7-tdd-refactoring-with-polymorphism 8-tdd-refactoring-with-polymorphism

As you can see, now GetPayroll() is able to use the same method for all class types by targeting the interface of the employee classes, not their implementation.


Now I’m ready to test my code to ensure it passes.

10-tdd-refactoring-with-polymorphism 11-tdd-refactoring-with-polymorphism

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s