Duplicated Code


Symptoms

  • The easy form: Two fragments of code look nearly identical.

  • The hard form: Two fragments of code have nearly identical effects (at any conceptual level).

Causes

Some duplication occurs because programmers work independently in different parts of the system, and they don't realize that they are creating almost identical code. Sometimes people realize there's duplication, but they're too lazy to remove it. Other times, duplication will be hidden by other smells; once those smells are fixed, the duplication becomes more obvious.

A worse -case (but perhaps the most common) scenario occurs when the programmers intentionally duplicate code. They find some code that is almost right, so they copy and paste it into the new spot with some slight alterations.

What to Do

  • If the duplication is within a method or in two different methods in the same class : Use Extract Method to pull the common part out into a separate method.

  • If the duplication is within two sibling classes : Use Extract Method to create a single routine; then use Pull Up Field and/or Pull Up Method to bring the common parts together. Then you may be able to use Form Template Method to create a common algorithm in the parent and unique steps in the children.

  • If the duplication is in two unrelated classes : Either extract the common part into a new class via Extract Class , or decide that the smell is Feature Envy (see Chapter 10) so the common code really belongs on only one class or the other.

  • In any of these cases, you may find that the two places aren't literally identical but that they have the same effect. Then you may do a Substitute Algorithm so that only one copy is involved.

Payoff

Reduces duplication. Lowers size. Can lead to better abstractions and more flexible code.

Contraindications

In very rare cases, you may conclude that the duplication communicates significantly better and decide to leave it in place. Or you may have duplication that is only coincidental; in this case, folding the two places together would only confuse the reader.



Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net