Sunday, September 7, 2008

Code duplication, DRY and Refactoring

Recently i had a chance to look at some development code. The code base  contains lots of duplicated code. It's really disappointing even the experienced developers doing this bad practice.

       Code duplication is the result of copy paste reuse. Imagine that  you have duplicated a method in "n" number of places. After some time if you need to change that method you have to do it in "n" different places.It's really a nightmare for everyone who does the change.Code duplication increases the complexity of the code base and increases the maintenance activity. So please don't duplicate the code. Try to avoid it as much as you can. The experts say "code duplication is the fundamental programming sin and it is the number one code smell."

In this context it would be good to know one fundamental and well known principle when building systems. The DRY principle. Even though DRY is far grander than just code duplication it would be pretty useful to know and follow. DRY is an acronym of "Don't Repeat Yourself" . DRY principle states that "Every piece of knowledge must have unique, unambiguous and representation within the system. DRY is applicable for many things such as architecture, requirements, code, test, documentation etc when building systems.DRY helps us to reduce the coupling and improves the orthogonality of knowledge within the system.

If you are really interested in refactoring please apply the following refactorings to avoid code duplication.
  1. Extract method - Use this when you have the same statements or expressions duplicated within the class.
  2. Extract class - Use this when you have duplicated methods in different places and invoke the extracted class from different places.
  3. Form Template method - Use this when you have the subclasses of methods do the same thing with the different algorithm.
  4. Pull up field - Use this when you have the same field in different subclasses inheriting from the same parent.
So please don't duplicate the code. I wish this should be the last time i violate the DRY principle.

1 comment:

  1. Nice Information about DRY and the last statement was classic.

    ReplyDelete