[java] UseStringBufferForStringAppends: False Positive with ternary operator
A source code analyzer
Brought to you by:
adangel,
juansotuyo
Cannot reproduce with PMD 5.3.1
To trigger the bug, you must define the variable in one statement and perform the append in other.
Here two examples that triggers the bug (tested onsrc/test/resources/net/sourceforge/pmd/lang/java/rule/optimizations/xml/UseStringBufferForStringAppends.xml)
Example1:
public class UseStringBuffer {
public void foo() {
String country = "";
country = (country == null || "".equals(country))
? ((String) getCountry())
: country;
}
}
Example2:
public class UseStringBuffer {
public void foo() {
String country = request.getParameter("country");
country = (country == null) ? "USA" : country;
}
}
This bug will be fixed with PMD 5.3.7, 5.4.2 and 5.5.0.
See PR https://github.com/pmd/pmd/pull/85
Last edit: Andreas Dangel 2016-04-30
This bug is reproducible with the inverse case on 5.5.3. If you flip the condition and arguments, it will raise a violation.
public class UseStringBuffer {
public void foo() {
String country = request.getParameter("country");
country = (country != null) ? country : "USA";
}
}
Thanks for letting us know. I've create a new ticket over there -> https://github.com/pmd/pmd/issues/222