Repository navigation
Closed
Description
Rule Set:
<rule ref="rulesets/java/basic.xml"/>
<rule ref="rulesets/java/braces.xml"/>
<rule ref="rulesets/java/codesize.xml"/>
<rule ref="rulesets/java/coupling.xml">
<exclude name="LawOfDemeter"/>
<exclude name="LoosePackageCoupling"/>
</rule>
<rule ref="rulesets/java/design.xml">
<exclude name="UseVarargs"/>
<exclude name="UseUtilityClass"/>
<exclude name="SingularField"/>
<exclude name="CloseResource"/>
</rule>
<rule ref="rulesets/java/empty.xml"/>
<rule ref="rulesets/java/imports.xml"/>
<rule ref="rulesets/java/naming.xml/LongVariable" />
<rule ref="rulesets/java/naming.xml/ClassNamingConventions" />
<rule ref="rulesets/java/naming.xml/MethodWithSameNameAsEnclosingClass" />
<rule ref="rulesets/java/naming.xml/SuspiciousHashcodeMethodName" />
<rule ref="rulesets/java/naming.xml/SuspiciousConstantFieldName" />
<rule ref="rulesets/java/naming.xml/SuspiciousEqualsMethodName" />
<rule ref="rulesets/java/naming.xml/AvoidFieldNameMatchingTypeName" />
<rule ref="rulesets/java/naming.xml/PackageCase" />
<rule ref="rulesets/java/naming.xml/BooleanGetMethodName" />
<rule ref="rulesets/java/optimizations.xml/UseArrayListInsteadOfVector" />
<rule ref="rulesets/java/optimizations.xml/UseArraysAsList" />
<rule ref="rulesets/java/optimizations.xml/AvoidArrayLoops" />
<rule ref="rulesets/java/optimizations.xml/UnnecessaryWrapperObjectCreation" />
<rule ref="rulesets/java/typeresolution.xml/LooseCoupling"/>
<rule ref="rulesets/java/typeresolution.xml/UnusedImports"/>
<rule ref="rulesets/java/unnecessary.xml"/>
Description:
False positive when making a clone of a hashmap
Code Sample demonstrating the issue:
public class CustomerErrorCollector {
private final ConcurrentHashMap<String, String> customerErrors = new ConcurrentHashMap<>();
public void error(String customerNr, String errorMsg) {
customerErrors.put(customerNr, errorMsg);
}
public Map<String, String> getAndReset() {
final Map<String, String> copy = new HashMap<>(customerErrors);
customerErrors.clear();
return copy; // PMD complains that variable could be avoided
}
}
Running PMD through: Gradle
Activity
jsotuyod commentedon Mar 2, 2017
@posto thanks for the report! I'll look into it.
One little advice though, your code seems to try to be thread-safe (uses
ConcurrentHashMap) but isn't. Items added by another thread between copying all elements tocopyand callingclear()would be lost. You would probably rather docustomerErrors.keySet().removeAll(copy.keySet())instead of simply callingclear()to avoid this.NickButcher1 commentedon Mar 2, 2017
I see many false positives with UnnecessaryLocalBeforeReturn after upgrading PMD 5.5.3 -> 5.5.4.
For example:
And (simplified from my actual code):
Thanks for your help.
jsotuyod commentedon Mar 13, 2017
Just submitted a PR fixing these scenarios, should be part of the next PMD release.
[java] Fix FP on UnnecessaryLocalBeforeReturn
Update changelog, references pmd#282