Tuesday, February 16, 2010

OO Design and Eclipse VS Code Duplication and Copy-paste

"It has a duplication that is painful to my eye"
- Martin Fowler Analysis patterns

The fundamental problem with copy paste is code duplication. Code duplication brings many issues with it, explained in several books and principles, like the "DRY" principle in "The Pragmatic Programmer", or the "Minimize Repetition" principle in "Implementation Patterns". So what's the problem with duplication? In Kent Beck words:

"Duplication isn’t evil, it just raises the cost of making changes."
- Kent Beck, Implementation Patterns.

Why it raises the cost of making changes? Here are a few reasons:
  • Change a thing in duplicate code means change in several places.
  • Do all need to change? The cost of changing them all is the number of copies you have.
  • If the code duplicated has a bug, there is not a single reference where to fix it.
  • You drag everything - coping a method but then you forget to change the documentation, the variable names etc...

Object Oriented Design vs Code Duplication.

When you start seeing code duplication, your code will be shouting that there is a missing abstraction. In that case you can do one of the following refactors:

  • Extract Method - For code duplication in the same class.
  • Extract Class - Some methods are only related to some data on your class, it time to break it down.
  • Form Template Method - Sometimes you are copy-pasting procedures or algorithms. In that case use the Template method pattern and possibly turn it into his own Class. A good example for this is the JDBCTemplate in the spring framework. Also a good read explaining how this work is the article Avoiding Repetition by Martin Fowler.

What about static methods?

Its common in Java world to avoid duplication using static methods, but they loose the biggest benefits in OO programing, a local context that simplify the logic. And don't forget that it also makes Unit Testing Harder. So try to avoid them as a solution to avoid code duplication.

Not completely against static methods. Just be sure that you are not missing an abstraction. There can a be a new object that is waiting to come alive. Take a look at "replace Method with Method Object".

Eclipse vs Copy Paste

Once creating a level of abstraction is not longer beneficial, do not use copy paste. Let your IDE do the work for you. All Modern IDE have a template solution a few key strokes away - In eclipse you would never type "System.out.println()" do you? you would do "sysout" then Ctrl+Space. Here is a list of article on how to create your own templates:

The three strikes rule

Use the three strikes rule, copy-paste one, copy-paste two, copy-paste three, Refactor! - or at least create the eclipse template ;) .