0

I have an enum class with several key. A number of keys should have the same string value. Sonar yells at me to replace the same string values with a constant value.

For example:

public enum MESSAGE_TYPES {

KEY1("Val1"),
KEY2("Val2"),
KEY3("Val3"),
KEY4("Val2"),
KEY5("Val4"),
KEY6("Val2"),
//etc.

}

So, sonar wants me to :

Define a constant instead of duplicating this literal...

for "Val2" since it is defined 3 or more times. How can I achieve that?

Auto extracting the value to a constant puts it right after the enum keys, but then the value of the enum key doesn't recognize it of course. So, I tried to put it on top of the enum class

public enum MESSAGE_TYPES {

    private static final String VAL2 = "Val2";

    KEY1("Val1"),
    KEY2(VAL2),
...
}

and so I get "Syntax error" errors on the line.

Please advise.

Thanks!

dushkin
  • 1,939
  • 3
  • 37
  • 82
  • https://stackoverflow.com/questions/23608885/how-to-define-static-constants-in-a-java-enum#23609178 i think this could help you :) – Claudio Brasser Aug 15 '17 at 14:28
  • Unrelated: read about java naming convents. enum CONSTANTS go uppercase, but the name of the enum class ... is just like an ordinary **class** name, thus it should be MessageTypes for example! – GhostCat Aug 15 '17 at 14:29

1 Answers1

4

You cannot declare static fields in an enum class before declaring the enum values.
And declaring static fields after the enum values will not allow to use them in the enum constructor.
So just extract the String values in a class and reference them in the enum values declaration.

For example :

public final class MyMessageConstant{

    public static final String VAL1 = "Val2";
    public static final String VAL2 = "Val2";

    private MyMessageConstant(){
    }
}

And the enum :

public enum MESSAGE_TYPES {

    KEY1(MyMessageConstant.VAL1),
    KEY2(MyMessageConstant.VAL2),
...
}

If it makes sense to keep the String values private to the enum class, you can declare the constant class as a private static final class member of the enum :

public enum Types {

    KEY1(MyMessageConstant.VAL1), KEY2(MyMessageConstant.VAL2),...
    KEY4(MyMessageConstant.VAL2),

    private static final class MyMessageConstant {        
       private static final String VAL1 = "Val2";
       private static final String VAL2 = "Val2";        
       private MyMessageConstant() {}
    }

    private String value;

    private Types(String value) {
      this.value = value;
    }

}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I also have question related to enums [here](https://stackoverflow.com/questions/47956136/how-can-i-represent-key-with-list-of-values-for-each-environment-type-in-an-enum/). Wanted to see whether we can represent that easily with enums or not. – user1950349 Dec 27 '17 at 05:27
  • I did an answer as rather clear and nice question. – davidxxx Dec 27 '17 at 14:30