Monday, June 23, 2014

Duplicated Code and how to eliminate them

Number one in the stink program is duplicated code. If you see the same code block in more than one place, you can be sure that your program will be better if you find a way to unify them.
 
. When you see the same block of code in two methods of the same class, extract the code block into a private method and invoke the method from both places.
 
.when you see the same block of the code in 2 sibling sub-classes, extract the code block into a protected method in the base class and invoke the method in both places.
 
.When you see the code block are doing the same thing but in different way, extract the better code block into a private method and invoke the method in both places.
 
.When you see the duplicated code blocks are doing the same but on different target, extract the code block into a private method with some parameters, and then invoke the method in both places with different parameter values.
 
.When you see a duplicated code block in 2 unrelated classes, you have a few options. You need to decide which one make more sense from business point of view.
a.       Abstract the duplicated code blocks into an abstract base class and let the 2 classes inherit from it. (Be its sub-class). In another word, make them related by be the sub classes of the same base class.
b.      Encapsulate the code block in third class as internal/public read only property or method and invoke it in both place. This will also reduce class coupling.
c.       Abstract the code block into a public method in one class and let other class invoke the method in the hosting class. 
 

No comments:

Post a Comment