You are right, there is no specific option for this rule, to explicitly ignore hashCode
and equals
methods. However, it should be possible now via suppressions. Every rule has a "violationSuppressXPath" property - and it seems, that this is used for this rule in a way, that it should work with this use case: It's not only applied for the violations, but also while analyzing the source code.
Here's the source code for CyclomaticComplexityRule which inherits from StdCyclomaticComplexityRule. If you look at line 188, you'll see that the method node is checked for any suppressions. If the method is suppressed, then it is not analyzed and should not be counted towards the class complexity. [See update below].
A possible XPath expression for violationSuppressXPath
might look like this:
./MethodDeclarator[@Image='hashCode' or @Image='equals']
You'll need to use a custom ruleset, in order to configure the property. You're ruleset might look like this:
<?xml version="1.0"?>
<ruleset name="Custom 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>CyclomaticComplexity ignoring hashCode and equals</description>
<rule ref="rulesets/java/codesize.xml/CyclomaticComplexity">
<properties>
<property name="violationSuppressXPath" value="./MethodDeclarator[@Image='hashCode' or @Image='equals']"/>
</properties>
</rule>
</ruleset>
Please note, that my examples use PMD 5.4.x - which is much newer than PMD 4.3 you referred to. The rule organization has been changed in order to support multiple languages - this means, the rule reference for PMD 4.3 would be just rulesets/codesize.xml/CyclomaticComplexity
.
Update (2016-05-20)
With the configured violationSuppressXPath property, the methods "equals" and "hashCode" are not highlighted anymore. Only the violation messages are suppressed. However the content of the method still does count to the total complexity of the class, so that any conditions/if statements/loops/etc. are checked (this is because super.visit()
is called before suppression at line 186) and because the isSuppressed
check only understands annotations.
This means, while the method itself is not highlighted anymore, the class is, because it contains a complex method.
The only way to completely ignore the equals/hashCode methods is, to annotate these with
@SuppressWarnings("PMD.CyclomaticComplexity")
Then, they are totally ignored and really do not count towards the class complexity.