javaeclipsepmd

How to ignore "id" in Short Variable rule using PMD


I am using PMD plugin (version 4.0.2) for Eclipse (Eclipse Kepler Java EE). I have configured a naming rule: ShortVariable.

This works fine except for parameters like "id" and "e". I want PMD to ignore these. So I searched for a way to ignore certain parameters. I found this link (although it's for phpmd) and tried it, yet I can't seem to get it working. My config file looks like this (XML):

<?xml version="1.0"?>
<ruleset name="My PMD ruleset"
 xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
    <description>
        My PMD
    </description>
    <rule ref="rulesets/java/naming.xml/ShortVariable">
        <property name="exceptions" value="id" />
    </rule>
</ruleset>

When I try to import this ruleset using the eclipse plugin, it shows no possible rules to import. Any ideas?


Solution

  • I found a solution to my problem here.

    The resulting xml looks like this:

    <?xml version="1.0"?>
    <ruleset name="My PMD ruleset"
     xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
        <description>
            My PMD
        </description>
        <rule ref="rulesets/java/naming.xml/ShortVariable">
            <properties>
                <property name="xpath">
                    <value>
                        //VariableDeclaratorId[(string-length(@Image) &lt; 3) and (not (@Image='id'))]
                        [not(ancestor::ForInit)]
                        [not((ancestor::FormalParameter) and (ancestor::TryStatement))]
                    </value>
                </property>
            </properties>
        </rule>
    </ruleset>
    

    To be able to ignore more variable names, repeat the following part:

    and (not (@Image='myVariableToIgnore'))