Saturday, April 12, 2008

Refactroing : Handling Duplicate Code

In legacy code bases we see lot of duplicate code . so how do we handle it ?

I am assuming you are using a tool that supports refactoring . In that case ,

Case 1:

If in a class you have lot of repeated code , use extract method refactoring to move the repeated code into a common method inside the class . Now replace if not automatically all occurance s of the repeated code with the call to the newly created method.

Case 2:

You have 2 sibling classes that have same piece of code .

Use extract method to create method with the same name in the 2 classes . Then use pull up refactoring to pull up the common method now in a super class . If the super class does not exist create it now .

Case 3:

You have 2 sibling classes that have almost the same piece of code , but some different bits here and there .

Use extract method to create method with the same signature in both the classes . Then identify the parts that are different , extract these different parts into methods of their own . Make sure that the names of these different parts is same in both sibling classes.

Now use template method design pattern , to create a common method in a super class of these 2 siblings . Using polymorph ism and inheritance to implement the different methods in the sibling classes.

No comments: