Duplicate Code

A class that does too much and has no clear responsibility, is "a splendid breeding place for duplicated code, chaos and death" (Martin Fowler). Duplicated code makes software maintenance more difficult, since all duplicates of one piece of code must be kept consistent, and a defect that has been found in duplicated code cannot be fixed in just one spot.

The PHP Copy/Paste Detector) can be used to automatically detect duplicated code in a PHP project. Example 4-4 shows how to invoke it from our Apache Ant build script.

Example 4-4. The phpcpd build target for the PHP Copy/Paste Detector

<target name="phpcpd" description="Find duplicate code using PHPCPD">
 <exec executable="phpcpd">
  <arg value="--log-pmd" />
  <arg value="${basedir}/build/logs/pmd-cpd.xml" />
  <arg path="${basedir}/src" />
 </exec>
</target>

Figure 4-4 shows how to configure a post-build action in our Jenkins job to publish the results of the analysis performed by the PHP Copy/Paste Detector.