Tuesday, September 06, 2011

SOLUTION: Modify PMD's ShortVariable Rule To Ignore ID Fields

Several people online have asked about the problem of not being able to add exceptions to PMD's ShortVariable rule. Most often, it has been the desire to get PMD to ignore the case where the variable name is 'id'. I was not able to find a solution online, but I worked with the XPath until I came up with a working solution.

  1. In Eclipse, go to Window » Preferences » PMD » Rules configuration » ShortVariable » Edit Rule...
  2. Change the XPath field to:
    //VariableDeclaratorId[(string-length(@Image) < 3) and (not (@Image='id'))]
    [not(ancestor::ForInit)]
    [not((ancestor::FormalParameter) and (ancestor::TryStatement))]
  3. Click Apply » Confirm rebuild » Click Ok » Confirm rebuild
  4. Restart Eclipse
  5. Right-click on the project » PMD » Check code with PMD
    1. You should then see the warning markers disappear on your id fields.

No comments: