6

How can I avoid the PMD error in my Java code?

public enum testEnum {

    TEST1(1L, "TEST", "random1");
    TEST2(2L, "TEST", "random2");
    TEST3(3L, "TEST", "random3");
    TEST4(4L, "TEST", "random4");
    TEST5(5L, "TEST", "random5");
    TEST6(6L, "TEST", "random6");
    TEST7(7L, "OTHER STRING", "random7");

    private Long id;
    private String type;
    private String text;

    private testEnum(Long id, String type, String text){
      this.id = id;
      this.type = type;
      this.text = text;
    }
}

When running PMD checks it throws these error:

The String literal "TEST" appears 6 times in this file; the first occurrence is on line 10

Is there any way to avoid it instead of using @SuppressWarnings("PMD")?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • Even though it's not very good practice to repeat Strings, it's not an error, rather a 'warning' or 'informational message' – Stultuske Sep 04 '15 at 07:13

3 Answers3

8

There are sometimes good reasons to disable this or that PMD warning. The way to disable a specific warning is to add the explicite rule to the suppressions. Here it is:

@SuppressWarnings("PMD.AvoidDuplicateLiterals")

This also works with all other rules.

bebbo
  • 2,830
  • 1
  • 32
  • 37
  • 2
    Thank you. This is really the correct answer. There are numerous cases in which we wish to use the same String literal - especially when outputting testing scenarios with similar output and different variables. – Ebony Maw Sep 03 '20 at 12:56
  • Case in point: annotations. You cannot replace a string in an annotation by a final static String, yet PMD will complain about it if a certain string appears too often. – SeverityOne Jul 08 '22 at 13:10
  • Sure, you can use final static String in annotations. There is only a caveat with arrays: Define the array in the annotation and use the final static String there. – bebbo Jul 09 '22 at 17:59
4

You should make a private static final String = "TEST"out of it. Repeat the same string is bad practice.

The best way to avoid this would be if you use more usefull string instead of "TEST".

SWiggels
  • 2,159
  • 1
  • 21
  • 35
  • Tip: in eclipse select one occurence of the litteral "TEST", right click "Refactor alt-shift T"/"extract constant". All occurences will be replaced – pdem Sep 04 '15 at 07:18
  • I did but the thing is I put the definition before creating enums so it threw an error on compilation time, it is solved when it is declared after them. –  Sep 04 '15 at 07:21
0

It is better to use constant instead of repeating the same String in several places, this will be better for the heap and for maintaining your code. You have only to modify in one place instead of looking where the "TEST" to change have been used. You can use : private static final String TEST = "TEST";

Aguid
  • 943
  • 2
  • 10
  • 24