Since PMD 6.0.0, all provided built-in rules are sorted into one of eight categories:
- Best Practices: These are rules which enforce generally accepted best practices.
- Code Style: These rules enforce a specific coding style.
- Design: Rules that help you discover design issues.
- Documentation: These rules are related to code documentation.
- Error Prone: Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
- Multithreading: These are rules that flag issues when dealing with multiple threads of execution.
- Performance: Rules that flag suboptimal code.
- Security: Rules that flag potential security flaws.
These categories help you to find rules and figure out the relevance and impact for your project.
There are two major use cases:
When defining a new rule, the rule needs to be defined in a ruleset. PMD’s built-in rules are defined in special rulesets which form the eight categories mentioned above. From these rulesets the rule reference documentation is generated, see Java Rules for an example.
Similar rules are grouped together into the same category, like Java Best Practices which contains rules which enforce generally accepted best practices. Each category uses its own ruleset file.
When executing PMD, you need to tell, which rules should be executed. You could directly point to the built-in rulesets, but then you might be overwhelmed by the found violations. As described in Best Practices, it’s better to define an own custom ruleset.
With an own custom ruleset, you can:
- Select the rules, that should be executed
- Adjust the rule properties to exactly meet your needs
Create a custom ruleset
You start by creating a new XML file with the following contents:
<?xml version="1.0"?> <ruleset name="Custom Rules" 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> Custom rules </description> </ruleset>
Now start to add rule by referencing them. Let’s say, you want to start with finding
Empty Catch Blocks. Then you’d add the following
rule reference inside the
<rule ref="category/java/errorprone.xml/EmptyCatchBlock" />
Adjusting rule properties
If you want to be less strict with empty catch blocks, you could define that an exception variable name
ignored will not raise a violation. Therefore you would reference the rule and define
the appropriate property value:
<rule ref="category/java/errorprone.xml/EmptyCatchBlock"> <properties> <property name="allowExceptionNameRegex"> <value>^ignored$</value> </property> </properties> </rule>