Skip to content

[java] AvoidLiteralsInIfCondition false positive and negative for String literals when ignoreExpressions=true #4514

@adangel

Description

@adangel

Affects PMD Version: 6.x

Rule: AvoidLiteralsInIfCondition

Description:

String literals are reported for deeper expressions when the property ignoreExpressions is true (that's the default value).

Note: This is fixed already with PMD 7.0.0-rc1.
Found via #3123 .

Code Sample demonstrating the issue:

public class AvoidLiteralsInIfCondition {
    private static final int MY_CONSTANT = 1;
    public void test(int i, String s) {
        if ("test".equals(s)) {}      // expected violation is missing (false negative)
        if (i == 1) {}                // expected violation

        // the following literals should be ignored because ignoreExpression=true
        if (i == MY_CONSTANT && "test".equals(s)) {} // violation for "test" (false positive)
        if (i == 1 && "test".equals(s)) {}           // violation for "test" (false positive)
    }
}

Expected outcome:

PMD reports a violation at lines 8+9, but that's wrong. That's a false positive.
PMD doesn't report a violation at line 4, but that's wrong. That's a false negative.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of codea:false-positivePMD flags a piece of code that is not problematic

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions