Affects PMD Version:
7.7.0
Rule:
UseStringBufferLength
https://docs.pmd-code.org/latest/pmd_rules_java_performance.html#usestringbufferlength
Description:
Using UseStringBufferLength did not detect sb.toString().equals("")
in the following example.
Adding the following xpath expression to the rule definition file of UseStringBufferLength can solve this problem.
But I don't know if this modification method is appropriate. Please confirm.
|
(: finds sb.toString().equals("") :)
//MethodCall[pmd-java:matchesSig('_#equals(_)')
and MethodCall[pmd-java:matchesSig('java.lang.AbstractStringBuilder#toString()')]
and ArgumentList/StringLiteral[@Image='""']]
Code Sample demonstrating the issue:
public class UseStringBufferLengthTest { public void example1() { StringBuffer sb = new StringBuffer(); final String empty = ""; if (sb.toString().equals("")) {System.out.println();} // inefficient if (sb.toString().equals(empty)) {System.out.println();} // inefficient if (sb.length() == 0) {System.out.println();} // preferred if (sb.toString().length() == 2) {System.out.println();} // inefficient if (sb.length() == 2) {System.out.println();} // preferred } }
Expected outcome:
PMD does not report a violation at line if (sb.toString().equals("")) {System.out.println();}
, but that's wrong. That's a false negative.
Running PMD through: [CLI]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4