Information Technology Reference
In-Depth Information
And so it goes, the code duplication continues. Unless you know
whether the duplication is going up or down and where the duplication
is occurring, it's difficult to determine what problems you're heading
toward and where to refactor.
Solution
To create a solution, you first need to assess the problem. You can add
automated inspection tools such as PMD's CPD 7 or the Simian 8 static
analysis tools to report duplicate source code. We executed these
inspection tools as part of the build process so that we could run them
at any time. Using these tools, we determined the areas of code that
had the most duplication and then we generalized the code into com-
ponents. Using this approach, we were able to continually monitor our
code duplication and reduce the amount of duplicated code in the system.
In a typical scenario, you might discover that multiple classes have
the same or similar code. Follow these steps to reduce duplicate code.
1. Analyze the code using a code duplication analyzer such as
Simian or PMD's CPD. Incorporate this into your build script.
2. Reduce the duplicated code by refactoring 9 the code into a sin-
gle method or component that is called by the classes where it
used to appear.
3. Run code duplication inspections continuously by incorporating
a code duplication inspector into your CI system. This gives you
the capability to determine code duplication over time.
Chapter 7 details the inspections you can run, how often, and when
to apply them.
7. CPD, a utility of the PMD metrics tool, reports instances of copied and pasted
source code. It is available at http://pmd.sourceforge.net/.
8. Simian (Similarity Analyser) provides support for C#, Java, Ruby, and a number
of other languages. It is available for download at www.redhillconsulting.com.au/
products/simian/.
9. “Refactoring is making changes to a body of code in order to improve its inter-
nal structure, without changing its external behavior.” From “Refactoring with
Martin Fowler: A Conversation with Martin Fowler, Part I,” by Bill Venners, at
www.artima.com/intv/refactor.html.
Search WWH ::




Custom Search