SonarQube: Should magic numbers be allowed in java constructor enums

1.6k views Asked by At

Concerning rule squid: S109 Magic numbers should not be used

Shouldn't it be allowed to have numbers in the constructor of an enum in java? The code below shouldn't violate the rule in my opinion.

public enum Color{
   RED(42),
   GREEN(123456),
   BLUE(666);

   public final int code;

   Color(int colorCode){
      this.code=colorCode;
   }    
}

I'm using Sonar java plugin version 3.3

2

There are 2 answers

0
Dams On BEST ANSWER

It will be fixed in version 3.4

See this issue on SonarSource : http://jira.sonarsource.com/browse/SONARJAVA-1117

1
kucing_terbang On

Technically, yes there is nothing wrong with your code. The code shows that the color code for each enum type is based on the constructor (like red is 42). But, squid rule dictates that this could be "confusing" when someone is trying to debug the code (particularly, a big piece of code).

This is taken from the squid rule documentation.

Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time.

That is why magic numbers must be demystified by first being assigned to clearly named constants before being used.

-1, 0 and 1 are not considered magic numbers

So, in your code, you may want to do something like this.

public enum Color{
   public final int RED_CODE = 42;
   RED(RED_CODE);

   public final int code;

   Color(int colorCode){
      this.code=colorCode;
   }    
}

or might as well disable the rule :D