Skip to content

[java] ImmutableField false positive with multiple constructors #1151

@AustinShalit

Description

@AustinShalit

Affects PMD Version: 6.3.0 and before

Rule: ImmutableField

Description:
The ImmutableField rule can detect false positives when you have multiple constructors that call this() on each other.

Code Sample demonstrating the false positive:

public class AnalogAccelerometer {
  private AnalogInput m_analogChannel;
  private boolean m_allocatedChannel; // Violation

  public AnalogAccelerometer(final int channel) {
    this(new AnalogInput(channel));
    m_allocatedChannel = true;
  }

  public AnalogAccelerometer(final AnalogInput channel) {
    m_allocatedChannel = false;
    m_analogChannel = channel;
  }
}

Code Sample demonstrating the issue if I listened to PMD's recommendation:

public class AnalogAccelerometer {
  private AnalogInput m_analogChannel;
  private final boolean m_allocatedChannel;

  public AnalogAccelerometer(final int channel) {
    this(new AnalogInput(channel));
    m_allocatedChannel = true; // error: variable m_allocatedChannel might already have been assigned
  }

  public AnalogAccelerometer(final AnalogInput channel) {
    m_allocatedChannel = false;
    m_analogChannel = channel;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueA great starting point for new contributorsin:documentationAffects the documentation [doc]

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions