Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[java] ConsecutiveLiteralAppends and InsufficientStringBufferDeclaration: FP with switch expressions #3152

Closed
adangel opened this issue Mar 4, 2021 · 0 comments · Fixed by #3154
Assignees
Labels
a:false-positive PMD flags a piece of code that is not problematic
Milestone

Comments

@adangel
Copy link
Member

adangel commented Mar 4, 2021

Since PMD 6.27.0, still in the latest 6.32.0, needs at least Java15 due to Switch Expressions

Rules: ConsecutiveLiteralAppends and InsufficientStringBufferDeclaration

I encountered similar issues, with PMD 6.31.0/6.32.0

the following code are causing both PMD.InsufficientStringBufferDeclaration, PMD.ConsecutiveLiteralAppends
PMD 6.30.0 works fine

public class FalsePositive {

    public static String escapeHTML(String text) {
        int length = text.length();
        int index = findHTMLReservedChar(text);
        if (index == length) return text;
        var builder = new StringBuilder(length * 2); // Rule:InsufficientStringBufferDeclaration Priority:3 StringBuffer constructor is initialized with size 16, but has at least 29 characters appended..
        for (int i = 0; i < index; i++) builder.append(text.charAt(i));
        for (; index < length; index++) {
            char ch = text.charAt(index);
            switch (ch) {
                case '<' -> builder.append("&lt;"); // Rule:ConsecutiveLiteralAppends Priority:3 StringBuffer (or StringBuilder).append is called 6 consecutive times with literals. Use a single append with a single combined String..
                case '>' -> builder.append("&gt;");
                case '"' -> builder.append("&quot;");
                case '&' -> builder.append("&amp;");
                case '\'' -> builder.append("&#39;");
                case '/' -> builder.append("&#47;");
                default -> builder.append(ch);
            }
        }
        return builder.toString();
    }
    
    private static int findHTMLReservedChar(String text) {
        return 0;
    }
}

Originally posted by @neowu in #2427 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a:false-positive PMD flags a piece of code that is not problematic
Projects
None yet
1 participant