This is the third in a series of posts which have the ant targets and javascript to generate and report on source code derived quality metrics.

PMD

PMD is similar to FindBugs in that it produces a list of potential problems, including:

  • Possible bugs – empty try/catch/finally/switch statements
  • Dead code – unused local variables, parameters and private methods
  • Suboptimal code – wasteful String/StringBuffer usage
  • Overcomplicated expressions – unnecessary if statements, for loops that could be while loops
  • Duplicate code – copied/pasted code means copied/pasted bugs

Unlike FindBugs however, it works from the source code, not the byte code. The list of rules it applies can be found here.

Here is the ant task.

<!-- pmd -->
<target name="pmd">
 <taskdef name="pmd"
          classname="net.sourceforge.pmd.ant.PMDTask"
          classpath="${metrics.dir.lib}\\pmd\\lib\\pmd-3.9.jar"/>

 <pmd shortFilenames="true">
  <ruleset>basic</ruleset>
  <formatter type="xml"
             toFile="${metrics.dir.report}\\xml\\${report.name}"
             linkPrefix="http://pmd.sourceforge.net/xref/"/>
  <fileset dir="${dir.source}" includes="**\\*.java"/>
 </pmd>
</target>

Variables:

  • metrics.dir.lib – Tell ant how to find the the pmd task in a decoupled manner. I try not to put these in the main ant lib dir.
  • metrics.dir.report – The place where you want the report put. In this case, my reports dir has ‘xml’, ‘xsl’ and ‘html’ dirs for organization of the various parts of the report generation process.
  • report.name – I call this target for each module I am collecting metrics for, so I pass in the name of the report as a parameter to it. Feel free to hardcode if that suits you better.
  • dir.source – Since PMD works on the actual sourcecode, you need to specify where the top-level dir that contains it. Note that if you have a package called org.agoucher.metrics, it would be the dir that contains the ‘org’ dir.