SonarQube:java 构造函数枚举中是否应该允许幻数

SonarQube: Should magic numbers be allowed in java constructor enums

关于鱿鱼规则:不应使用 S109 幻数

在java的枚举的构造函数中不应该允许有数字吗?我认为下面的代码不应该违反规则。

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

   public final int code;

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

我正在使用 Sonar java 插件版本 3.3

从技术上讲,是的,您的代码没有任何问题。 代码显示每个枚举类型的颜色代码基于构造函数(如红色为 42)。但是,squid 规则规定,当有人试图调试代码(特别是一大段代码)时,这可能会“令人困惑”。

这取自鱿鱼规则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

所以,在您的代码中,您可能想要做这样的事情。

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

   public final int code;

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

或者也可以禁用规则 :D

3.4版本会修复

在 SonarSource 上查看此问题:http://jira.sonarsource.com/browse/SONARJAVA-1117