0

Example:

public enum TestEnum {
    FOO(4), BAR(7);

    public final int externalValue;

    private TestEnum(int externalValue) {
        this.externalValue = externalValue;
    }
}

Notice how there is no getExternalValue() method. Since the externalValue field is final, there's no risk of it getting modified. Running code like this through Sonar gives me a "Variable 'externalValue' must be private and have accessor methods" error.

Assume I'm a total moron, and explain: why do I absolutely need to implement and use an accessor for externalValue?

It's difficult to explain why, but the way the Java Bean pattern went from a clever construct to being a universal law, somehow upsets me. I just feel it shouldn't have to be necessary always.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
TV's Frank
  • 782
  • 7
  • 21

2 Answers2

1

The Sonar rule is simply wrong in this case; it's not even possible for an enum to conform to the JavaBean spec (since it requires a public constructor)

This always happens with static code analyzers; you can selectively disable certain warnings using a // NOSONAR comment or a @SuppressWarnings annotation.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • I think this is what I wanted to hear. :) I just think that if it was ok for an enum constant to have public final fields with accessors it shouldn't be that difficult to adjust the inspection in Sonar accordingly. – TV's Frank Feb 18 '13 at 12:31
0

If you see official documentation

Every instance final variable is declared private and their accessors are defined. So, may be it just has to be so?

sybear
  • 7,837
  • 1
  • 22
  • 38