Java Coding Style:static final Logger 的命名问题

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/sunknew/article/details/81121299

简述

最近公司要求使用PMD做静态代码检查时

private static final Logger logger = LoggerFactory.getLogger(Example.class);

此类代码会提示以下错误
A variable naming conventions rule - customize this to your liking. Currently, it checks for final variables that should be fully capitalized and non-final variables that should not include underscores.

这里写图片描述

分析

这里应该是默认使用 static final 修饰的 Logger 对象是常量,所以要求使用大写。
实际上并非如此,Java 与 C++ 不同,没有专门的关键字 const 用来定义常量。Java 常量使用 static final 修饰,但是用 static final 修饰的并不一定是常量。

The sole exception to the previous rule concerns “constant fields,” whose names should consist of one or more uppercase words separated by the underscore character, for example, VALUES or NEGATIVE_INFINITY. A constant field is a static final field whose value is immutable. If a static final field has a primitive type or an immutable reference type(Item 15), then it is a constant field. For example, enum constants are constant fields. If a static final field has a mutable reference type, it can still be a constant field if the referenced object is immutable.

—— Effective Java


Names of fields being used as constants should be all upper-case, with underscores separating words. The following are considered to be constants:

  • All static final primitive types (Remember that all interface fields are inherently static final).
  • All static final object reference types that are never followed by “.” (dot).
  • All static final arrays that are never followed by “[” (dot).


—— Achut Reddy - Java Coding Style Guide

用 final 修饰的变量只能赋值一次,但是这个值对于引用类型来说,只是一个引用地址,引用地址不变并不意味着其状态不可变(如,成员变量可变),所以一个引用类型若要作为常量还需要是不可变的(immutable )。

结论

结合 Java 常量的实现方式,Sun 的编程规范,slf4j 的示例等,此处使用小写完全没有问题。

参考

1.SLF4J FAQ : Should Logger members of a class be declared as static ?
2.Logging-FrequentlyAskedQuestions : Should I declare Log references static or not?
3.Should a -static final Logger- be declared in UPPER-CASE- - Stack Overflow
4.Why is there no Constant feature in Java - Stack Overflow
5.Logger (SLF4J 1.8.0-beta2 API)

猜你喜欢

转载自blog.csdn.net/sunknew/article/details/81121299