This is one of the easiest Refactorings to employ but it can be quite helpful. The example I'm going to use is quite simplified, so much so that it's probably oversimplified. Basically we have a conditional tree and depending on the Employee's title, his/her eligibility is set and SendToHR is set passing in their respective eligibility. This is a very simple example but I've definitely seen many where code is copied and pasted and done a few times. Before you know it you have a good bit of code that's redundant. When it's redundant, you have to make changes to every instance that calls it. This is a maintenance nightmare and it tends to make things more difficult to read and obscures one's intent.
Fortunately, fixing it is one of the easiest things to implement:
First, note that I've added two new fields to the Employee class, Title and Eligible. This is a horrible implementation and it's intentional because I intend to introduce another refactoring based on it. Nonetheless, let's assume we're fixing things in an assembly line..so we fix all Problem x's before we move on to Problelm Y's.
Here's the Employee Class:
| using System; namespace RefactorSamples { /// <summary> /// Summary description for Employee. /// public class Employee { private Name empName; private string title; private bool eligible; public Employee() { // // TODO: Add constructor logic here // } public Employee(string first, string last) { } public Name EmployeeName { get{return empName;} set{empName = value;} } public string Title { get{return title;} set{title = value;} } public bool Eligible { get{return eligible;} set{eligible = value;} } } } |
| private void btnConsolidate_Click(object sender, System.EventArgs e) { Employee emp = new Employee(); switch(emp.Title) { case "President": emp.Eligible = true; SendToHR(emp.Eligible); SendToPayRoll(emp.Eligible); break; case "Vice President": emp.Eligible = true; SendToHR(emp.Eligible); SendToPayRoll(emp.Eligible); break; default: emp.Eligible = false; SendToHR(emp.Eligible); SendToPayRoll(emp.Eligible); break; } } private void SendToHR(bool eligible) { //Do Something } private void SendToPayRoll(bool eligible) { //Do Something } |
| private void btnConsolidate_Click(object sender, System.EventArgs e) { Employee emp = new Employee(); switch(emp.Title) { case "President": emp.Eligible = true; break; case "Vice President": emp.Eligible = true; break; default: emp.Eligible = false; break; } SendToHR(emp.Eligible); SendToPayRoll(emp.Eligible); } |