Skip to content

[java] Incorrect ImmutableField error on field with both declaration and constructor initializer #4046

@stevenschlansker

Description

@stevenschlansker

Affects PMD Version:
6.47.0

Rule:

Please provide the rule name and a link to the rule documentation:
Design.ImmutableField

Description:

ImmutableField sees an assignment that happens in a declaration or constructor, which would indicate the field may be final. But in the case where it is assigned in the declaration and constructor, it is no longer true that it may be final, but the rule still triggers.

Code Sample demonstrating the issue:

public class NotSoImmutableField {
    private int foo = 2;

    NotSoImmutableField() {
    }

    NotSoImmutableField(final int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return foo;
    }
}

Expected outcome:

The code is correct. PMD reports a violation:

[INFO] --- maven-pmd-plugin:3.17.0:check (basepom.default) @ wsj-util ---
[INFO] PMD version: 6.47.0
[INFO] PMD Failure: NotSoImmutableField:4 Rule:ImmutableField Priority:3 Private field 'foo' could be made final; it is only initialized in the declaration or constructor..

This warning is not correct. foo may not be final, since it is initialized both at declaration and in one of the constructors. Following the PMD recommendation results in a (correct) compiler error.

Running PMD through:
Maven

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions