SonarQube: If magic numbers are listed in the java constructor

Regarding the squid rule: S109 Magic numbers should not be used

Is it possible to have numbers in an enumeration constructor in java? The code below should not 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 am using Sonar version java plugin version 3.3

+5
source share
2 answers

It will be fixed in version 3.4.

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

+1
source

Technically, yes, there is nothing wrong with the code. The code shows that the color code for each type of enumeration is based on the constructor (for example, red - 42). But the squid rule dictates that it can be "confusing" when someone tries to debug code (in particular, a large piece of code).

This is taken from the squid rule.

Using magic numbers may seem obvious and simple when you write a piece of code, but they are much less obvious and understandable during debugging.

This is why magic numbers must be demystified by first assigning explicitly named constants before use.

-1, 0, and 1 are not considered magic numbers.

So in your code you can 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 may also disable the rule: D

0
source

All Articles