[java] UseStringBufferLength: false-negative on StringBuffer of sb.toString().equals("") #5320
Closed
Description
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]