Java 是否应该以大写形式声明“静态最终记录器”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1417190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should a "static final Logger" be declared in UPPER-CASE?
提问by dogbane
In Java, static final variables are constants and the convention is that they should be in upper-case. However, I have seen that most people declare loggers in lower-case which comes up as a violation in PMD.
在 Java 中,静态最终变量是常量,约定是它们应该是大写的。但是,我已经看到大多数人以小写形式声明记录器,这在PMD 中是一种违规行为。
e.g:
例如:
private static final Logger logger = Logger.getLogger(MyClass.class);
Just search googleor SOfor "static final logger" and you will see this for yourself.
只需在谷歌或SO 中搜索“静态最终记录器”,您就会亲眼看到这一点。
Should we be using LOGGER instead?
我们应该改用 LOGGER 吗?
采纳答案by crunchdog
The logger reference is not a constant, but a final reference, and should NOT be in uppercase. A constant VALUE should be in uppercase.
记录器引用不是常量,而是最终引用,不应大写。常量 VALUE 应为大写。
private static final Logger logger = Logger.getLogger(MyClass.class);
private static final double MY_CONSTANT = 0.0;
回答by Jo?o Silva
I personally think it looks really big in upper-case. Moreover, since it's a class that it's not directly related to the class behaviour, I don't see a major problem in using logger
instead of LOGGER
. But if you are going to be strictly pedantic, then use LOGGER
.
我个人认为它在大写中看起来非常大。此外,由于它是一个与类行为没有直接关系的类,因此我认为使用logger
代替LOGGER
. 但是,如果您要严格学究,请使用LOGGER
.
回答by Pete Kirkham
If you are using an automated tool to check your coding standards and it violates said standards then it or the standards should be fixed. If you're using an external standard, fix the code.
如果您使用自动化工具来检查您的编码标准并且它违反了所述标准,那么应该修复它或标准。如果您使用的是外部标准,请修复代码。
The convention in Sun Java is uppercase for public static constants. Obviously a logger is not constant, but represents a mutable thing ( otherwise there would be no point calling methods on it in the hope that something will happen ); there's no specific standard for non-constant final fields.
Sun Java 中的约定是公共静态常量的大写。显然,记录器不是常量,而是代表一个可变的东西(否则就没有必要在其上调用方法以希望某些事情会发生);对于非常量的 final 字段没有特定的标准。
回答by KLE
If you google this, you might find that in some cases, the loggers are not defined as static final. Add some quick copy-n-paste to this, and this might explain it.
如果你用谷歌搜索这个,你可能会发现在某些情况下,记录器没有被定义为静态最终的。对此添加一些快速复制粘贴,这可能会解释它。
We use LOGGERin all our code, and this corresponds to our naming convention (and our CheckStyle is happy with it).
我们在所有代码中都使用 LOGGER,这符合我们的命名约定(我们的 CheckStyle 对此很满意)。
We even go further, taking advantage of the strict naming convention in Eclipse. We create a new class with a code template of :
我们甚至更进一步,利用 Eclipse 中严格的命名约定。我们使用以下代码模板创建一个新类:
// private static final Logger LOGGER = Logger.getLogger(${enclosing_type}.class);
The logger is commented out, as initially we don't need it. But should we need it later, we just uncomment it.
记录器已被注释掉,因为最初我们不需要它。但是如果我们以后需要它,我们只需取消注释即可。
Then in the code, we use code templates that expect this logger to be present. Example with the try-catch template:
然后在代码中,我们使用期望这个记录器存在的代码模板。使用 try-catch 模板的示例:
try {
${cursor} or some other template
} catch (Exception t) {
LOGGER.error("${methodName} ${method parameters}", t);
}
We have a few more templates that use it.
我们还有一些使用它的模板。
The strict convention allow us to be more productive and coherent with code templates.
在严格的惯例使我们的工作效率和连贯的代码模板。
回答by Thorbj?rn Ravn Andersen
Usually constants are in uppercase.
通常常量是大写的。
Loggers, however, should not be static but looked up for every "new" of the containing class if using the slf4j facade. This avoids some nasty classloader issues in notably web containers, plus it allows the logger framework to do special stuff depending on the invocation context.
然而,如果使用 slf4j 外观,记录器不应该是静态的,而是查找包含类的每个“新”。这避免了特别是 web 容器中的一些讨厌的类加载器问题,此外它还允许记录器框架根据调用上下文做特殊的事情。
回答by Kutzi
If your coding standards - if you have any - say that it should be uppercase then yes.
如果你的编码标准——如果你有任何标准——说它应该是大写的,那么是的。
I don't see any stringent reason for one way or the other. I think it totally depends on your personal likes resp. your company coding standards.
我没有看到任何严格的理由。我认为这完全取决于您的个人喜好。您公司的编码标准。
BTW: I prefer "LOGGER" ;-)
顺便说一句:我更喜欢“记录器”;-)
回答by Fortyrunner
Don't forget that PMD will respect a comment with
不要忘记 PMD 会尊重评论
// NOPMD
in it. This will cause PMD to skip the line from its checks, this will allow you to choose whichever style you want.
在里面。这将导致 PMD 从其检查中跳过该行,这将允许您选择所需的任何样式。
回答by Jeffrey Blattman
From effective java, 2nd ed.,
来自有效的 Java,第二版,
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.
上一条规则的唯一例外涉及“常量字段”,其名称应由一个或多个由下划线字符分隔的大写单词组成,例如,VALUES 或 NEGATIVE_INFINITY。常量字段是一个静态的 final 字段,其值是不可变的。如果静态 final 字段具有原始类型或不可变引用类型(条款 15),则它是一个常量字段。例如,枚举常量是常量字段。如果静态 final 字段具有可变引用类型,并且引用的对象是不可变的,则它仍然可以是常量字段。
In summary, constant == static final, plus if it's a reference (vs. a simple type), immutability.
总之,constant == static final,加上如果它是一个引用(相对于一个简单类型),不变性。
Looking at the slf4j logger, http://www.slf4j.org/api/org/slf4j/Logger.html
查看 slf4j 记录器,http://www.slf4j.org/api/org/slf4j/Logger.html
It is immutable. On the other hand, the JUL logger is mutable. The log4j logger is also mutable. So to be correct, if you are using log4j or JUL, it should be "logger", and if you are using slf4j, it should be LOGGER.
它是不可变的。另一方面,JUL 记录器是可变的。log4j 记录器也是可变的。所以正确地说,如果你使用的是 log4j 或 JUL,它应该是“logger”,如果你使用的是 slf4j,它应该是 LOGGER。
Note that the slf4j javadocs page linked above has an example where they use "logger", not "LOGGER".
请注意,上面链接的 slf4j javadocs 页面有一个示例,其中他们使用“logger”,而不是“LOGGER”。
These are of course only conventions and not rules. If you happen to be using slf4j and you want to use "logger" because you are used to that from other frameworks, or if it is easier to type, or for readability, go ahead.
这些当然只是约定而不是规则。如果您碰巧正在使用 slf4j 并且您想使用“记录器”,因为您已经习惯了其他框架中的记录器,或者如果它更易于输入或为了可读性,请继续。
回答by cbliard
To add more value to crunchdog's answer, The Java Coding Style Guidestates this in paragraph 3.3 Field Naming
为了给 crunchdog 的答案增加更多价值,Java 编码风格指南在第 3.3 段字段命名中说明了这一点
Names of fields being used as constantsshould be all upper-case, with underscores separating words. The following are considered to be constants:
- All
static final
primitive types (Remember that allinterface fields are inherentlystatic final
).- All
static final
object reference types that are never followed by ".
" (dot).- All
static final
arrays that are never followed by "[
" (opening square bracket).Examples:
MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME
用作常量的字段名称应全部大写,并用下划线分隔单词。以下被认为是常数:
- 所有
static final
原始类型(请记住,所有接口字段都是固有的static final
)。- 所有
static final
对象引用类型后面永远不会跟“.
”(点)。- 所有
static final
从不后跟“[
”(左方括号)的数组。例子:
MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME
Following this convention, logger
is a static final
object reference as stated in point 2, but because it isfollowed by ".
" everytime you use it, it can not be considered as a constant and thus should be lower case.
遵循此约定,logger
是static final
第 2 点中所述的对象引用,但由于每次使用它时都后跟“ .
”,因此不能将其视为常量,因此应为小写。
回答by mateuscb
I like Google's take on it (Google Java Style)
我喜欢谷歌对它的看法(谷歌 Java 风格)
Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough.
每个常量都是静态 final 字段,但并非所有静态 final 字段都是常量。在选择常量案例之前,请考虑该字段是否真的感觉像一个常量。例如,如果该实例的任何可观察状态可以改变,它几乎肯定不是一个常数。仅仅打算永远不改变对象通常是不够的。
Examples:
例子:
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};