英文:
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 = "Freddie" // is a constant
private static final Map<String, String> myMap = new HashMap<>(); // 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<String, String> myMap = Map.of("One", "Blue", "Two", "Red");
是一个不可变值。
你可以做的一件事是告诉Checkstyle不要在私有字段上强制命名方案:
<module name="ConstantName">
<property name="applyToPrivate" value="false"/>
</module>
另一个选项是指定允许的名称:
<module name="ConstantName">
<property name="format"
value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|myMap|myLogger)$"/>
</module>
英文:
Not really. Checkstyle would have to execute the code. For instance, private static final Map<String, String> myMap = Map.of("One", "Blue", "Two", "Red");
is an immutable value.
One thing you can do is tell Checkstyle that it should not enforce the naming scheme on private fields:
<module name="ConstantName">
<property name="applyToPrivate" value="false"/>
</module>
Another option is to specify the permitted names:
<module name="ConstantName">
<property name="format"
value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|myMap|myLogger)$"/>
</module>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论