Skip to content

[java] ImmutableField: false-negative for field with a default + constructor assignment #4869

Open
@jsotuyod

Description

@jsotuyod

Under PMD 7.0.0 there is no report for the code:

public class NotSoImmutableField {
    private int foo = 2;

    NotSoImmutableField() {
    }

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

    public int getFoo() {
        return foo;
    }
}

The field is never written more than once within a given constructor, nor depends on the previous value. Therefore, the code can effectively be rewritten to make foo immutable, as it's never written after initialization, for instance, the code could be rewritten as:

public class NotSoImmutableField {
    private final int foo;

    NotSoImmutableField() {
        this(2);
    }

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

    public int getFoo() {
        return foo;
    }
}

Originally posted by @jsotuyod in #4046 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions