Skip to content

[java] ImmutableField - false negative when field assigned in constructor conditionally #3850

@MetaBF

Description

@MetaBF

Affects PMD Version: 6.43.0

Rule: ImmutableField

https://pmd.github.io/pmd-6.42.0/pmd_rules_java_design.html#immutablefield

Description:

Hi, I found a false-negative about rule ImmutableField, in this case, the private field str is only assigned in the constructor, therefore str could be final.

  • Code Example 1
public class ExampleImmutableField {

    private String str; // false negative here, could be final

    public ExampleImmutableField(String strLocal, boolean flag) { 
        if (flag){
            this.str = strLocal;
        } else {
            this.str = strLocal+"123";
        }
    }

}

I think it's probably due to wrong/limited control-flow analysis since PMD works fine in the following code.

  • Code Example 2
public class ExampleImmutableField {

    private String str; // PMD successfully reports warning here

    public ExampleImmutableField(String strLocal, boolean flag) {
            this.str = strLocal;
    }

} 

Expected outcome:

PMD should report a violation at line 3 in Code Example 1, but doesn't. This is a false-negative.

Running PMD through: [CLI]

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    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