A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pmd/pmd/issues/3712 below:

[java] InsufficientStringBufferDeclaration false positive with StringBuilder.setLength(0) · Issue #3712 · pmd/pmd · GitHub

Affects PMD Version: 6.41.0

Rule: InsufficientStringBufferDeclaration

Description:

When using StringBuilder.setLength(0) to reset the StringBuilder for reuse (to avoid allocating additional instances, especially in loops), PMD assumes that the builder length is 0 if it cannot determine the length from the constructor invocation, and warns about a too-small builder.

There does not seem to be an issue when the constructor uses a hardcoded size, only when the initial constructor size is calculated at runtime and PMD is unable to determine the actual initial size.

Code Sample demonstrating the issue:

    public static void foo(int i) {
        StringBuilder sb = new StringBuilder(i);
        sb.append("ab");
        sb.setLength(0); // false positive
        sb.append("cd");
    }

    public static void foo2() {
        StringBuilder sb = new StringBuilder(2);
        sb.append("ab");
        sb.setLength(0); // no problem, no false positive
        sb.append("cd");
    }

Expected outcome:

PMD reports a violation at line 4, but that's wrong. If PMD cannot determine the initial length from the constructor invocation, it should not assume that the length specified in setLength( ) is the maximum length -- especially when setLength(0) is used, which is basically always a request to reset the builder, not grow it.

Running PMD through: Gradle


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