Problems with Java enum duplicate literals

Please provide

  • Operating system: Windows 10 Pro
  • SonarLint plugin version: SonarLint for Eclipse
  • Programming language you’re coding in: Java
  • Is connected mode used:
    • Connected to SonarCloud or SonarQube (and which version): No

And a thorough description of the problem / question:
I received the following warnings on for enum value declerations, such as :

STRING("string", "String", true, "EMPTY", false, true, "String"),


Define a constant instead of duplicating this literal “EMPTY” 3 times. [+3 locations]
Define a constant instead of duplicating this literal “String” 20 times. [+20 locations]
However I don’t see how I can define such a constant.
Secondly, for the literal “’ '” no such warning is produced.

Hey there.

Can you provide a piece of code that in full demonstrates the issue? One line isn’t enough to analyze on our side.


image001.jpg (1.92 KB)

Hey Jonathan, sorry for the late reply. You could define constants to replace duplicate strings as follows:
Create a new class file, and define a constant class inside like

public static class Constants {
    public static final String EMPTY_VALUE = "Empty";
    public static final String STRING_VALUE = "String";

and you can put there whichever value you are duplicating if your code. Then in your enum you could just replace those "String" and "EMPTY" with Constants.STRING_VALUE and Constants.EMPTY_VALUE

Let me know if this solves your issue.

Dear Leonardo,

thanks, this solves the first problem. What about the second?

Hey Jonathan, sorry for the late response.
It’s mentioned at the bottom of the rule page, in the “exceptions” section, that literals shorter than 5 characters are ignored to avoid FPs

Thanks. I missed that.