Checkstyle 的 ConstantName 规则适用于那些实际上并不是常量的情况。

huangapple go评论69阅读模式
英文:

Checkstyle ConstantName rule kicks in for things that are not really constant

问题

我想检查我的字段名称是否仅针对符合我所偏好的“常量”定义的字段为大写,如Google的Java编码指南中所述。

因此:

private static final integer NUM = 1974;  // 是一个常量
private static final String NAME = "Freddie";  // 是一个常量

private static final Map<String, String> myMap = new HashMap<>();  // 不是常量
private static final Logger myLogger = LogManager.getLogger();  // 不是常量

是否可以指定一个规则,要求仅在类型为原始类型或对String或其他不可变类的最终引用时才使用大写命名?

英文:

I would like to check that my field names are uppercase only for fields that meet my preferred definition of "constant", as stated in Google's Java Coding Guidelines.

Thus:

private static final integer NUM = 1974;  // is a constant
private static final String NAME = &quot;Freddie&quot;  // is a constant

private static final Map&lt;String, String&gt; myMap = new HashMap&lt;&gt;();  // is NOT a constant
private static final Logger myLogger = LogManager.getLogger();  // is NOT a constant

Is it possible to specify a rule that requires uppercase naming only if the type is a primitive type or a final reference to a String or other immutable class?

答案1

得分: 2

不是真的。Checkstyle需要执行代码。例如,private static final Map&lt;String, String&gt; myMap = Map.of(&quot;One&quot;, &quot;Blue&quot;, &quot;Two&quot;, &quot;Red&quot;); 是一个不可变值。

你可以做的一件事是告诉Checkstyle不要在私有字段上强制命名方案:

<module name=&quot;ConstantName&quot;>
    <property name=&quot;applyToPrivate&quot; value=&quot;false&quot;/>
</module>

另一个选项是指定允许的名称:

<module name=&quot;ConstantName&quot;>
    <property name=&quot;format&quot;
        value=&quot;^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|myMap|myLogger)$&quot;/>
</module>
英文:

Not really. Checkstyle would have to execute the code. For instance, private static final Map&lt;String, String&gt; myMap = Map.of(&quot;One&quot;, &quot;Blue&quot;, &quot;Two&quot;, &quot;Red&quot;); is an immutable value.

One thing you can do is tell Checkstyle that it should not enforce the naming scheme on private fields:

&lt;module name=&quot;ConstantName&quot;&gt;
    &lt;property name=&quot;applyToPrivate&quot; value=&quot;false&quot;/&gt;
&lt;/module&gt;

Another option is to specify the permitted names:

&lt;module name=&quot;ConstantName&quot;&gt;
    &lt;property name=&quot;format&quot;
        value=&quot;^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|myMap|myLogger)$&quot;/&gt;
&lt;/module&gt;

huangapple
  • 本文由 发表于 2020年8月4日 01:08:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63233914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定