Pages

Sunday, May 23, 2010

PMD code checking: checking for programming against CDK interfaces

I wrote recently about programming against interfaces, which led to some discussion. Rajarshi commented:
    patch 2 seems to replace usage of Molecule with Molecule, rather than IMolecule
Now, this particularly problem was Eclipse being overly active cleaning up the imports, but we reached the point that it is actually interesting to have PMD warn about these issues. PMD is a cool piece of software used by the CDK project for a long time one. One particular cool thing is that you can write code warnings as XPath queries.

So, I promised Rajarshi to have a look at a custom rule to look at using IMolecule instead of Molecule. The code is actually pretty simple, using the aforementioned XPath feature:
<rule name="ReplaceMoleculeWithIMolecule"
      language="java"
      message="Use the IMolecule interfaces instead of the Molecule implementation"
      class="net.sourceforge.pmd.rules.XPathRule">
  <description>
      Programming against the CDK interfaces allows users to pick their favorite
      implementation (nonotify, datadebug).
  </description>
  <priority>3</priority>
  <properties>
    <property name="xpath">
      <value>
 <![CDATA[
   //Type/ReferenceType/ClassOrInterfaceType[@Image='Molecule']
 ]]>
      </value>
    </property>
  </properties>
    <example>
    <![CDATA[
      Molecule mol = builder.newInstance(IMolecule.class);
    ]]>
  </example>
</rule>
Patch pending...