Menu

#1340 [java] UseStringBufferForStringAppends: False Positive with ternary operator

PMD-5.3.7
closed
java (55)
PMD
3-Major
Bug
2017-01-30
2015-04-20
No

Please find the below sample code, which is throwing this exception.

country = (country == null || "".equals(country))
    ? ((String) getCountry())
    : country;

Discussion: https://sourceforge.net/p/pmd/discussion/188193/thread/a1ef16d2/

Related

Discussion: "Prefer StringBuffer over += for concatenating strings" - when using string reassignment with Ternary operator

Discussion

  • Andreas Dangel

    Andreas Dangel - 2015-05-01
    • status: open --> not-reproducible
    • assigned_to: Andreas Dangel
    • Milestone: New Tickets --> PMD-5.3.2
     
  • Andreas Dangel

    Andreas Dangel - 2015-05-01

    Cannot reproduce with PMD 5.3.1

     
  • Alberto Fernández

    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;
    }
    }

     
  • Andreas Dangel

    Andreas Dangel - 2016-02-28
    • status: not-reproducible --> closed
    • Milestone: PMD-5.3.2 --> PMD-5.3.7
    • Ruleset / Rule: -->
     
  • Andreas Dangel

    Andreas Dangel - 2016-02-28

    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
  • Andreas Dangel

    Andreas Dangel - 2016-06-25
    • labels: --> java
    • summary: UseStringBufferForStringAppends False Positive with ternary operator --> [java] UseStringBufferForStringAppends: False Positive with ternary operator
     
  • David Burström

    David Burström - 2017-01-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";
    }
    }

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.