在为脚本结果编写一些自定义流阅读器时,类中存在相当多的常量(主要用于预期的标记和关键字),我想知道是否存在任何类型的标准,约定或最佳实践来放置常量(在这里读取静态最终字段)在一个类中?
更具体地说,最好将每个常量放在类的顶部,或者将它们分组到它们有用的类的区域中,并将公共组合在顶部?
通过将所有内容放在顶部,在我看来,这可能更容易找到你在同一个地方寻找的所有东西,但如果这个区域越来越大,它会变得无法抗拒:
public class Test {
// Constants.
private static final String CLASSNAME = Test.class.getSimpleName();
private static final String COMMON = " = ";
private static final String CONSTRUCTOR = "#constructor";
private static final String METHOD_1 = "#method1";
private static final String METHOD_2 = "#method2";
public Test(String message) {
System.out.println(CLASSNAME + CONSTRUCTOR + COMMON + message);
method1(message);
method2(message);
}
private void method1(String message) {
System.out.println(CLASSNAME + METHOD_1 + COMMON + message);
}
private void method2(String message) {
System.out.println(CLASSNAME + METHOD_2 + COMMON + message);
}
public static void main(String[] args) {
new Test("Hello world!");
}
}
通过对它们进行分组,对于仅在类的特定区域中使用的常量更有意义,但它可能会破坏按类型添加到类中的良好对称效果分组,并且可能使其看起来很混乱:
public class Test {
// Common constants.
private static final String CLASSNAME = Test.class.getSimpleName();
private static final String COMMON = " = ";
// Constructor constants.
private static final String CONSTRUCTOR = "#constructor";
public Test(String message) {
System.out.println(CLASSNAME + CONSTRUCTOR + COMMON + message);
method1(message);
method2(message);
}
// Constant proper to method1(...).
private static final String METHOD_1 = "#method1";
private void method1(String message) {
System.out.println(CLASSNAME + METHOD_1 + COMMON + message);
}
// Constant proper to method2(...).
private static final String METHOD_2 = "#method2";
private void method2(String message) {
System.out.println(CLASSNAME + METHOD_2 + COMMON + message);
}
public static void main(String[] args) {
new Test("Hello world!");
}
}
输出:
Test#constructor = Hello world!
Test#method1 = Hello world!
Test#method2 = Hello world!
我知道这可能是一个主观的问题,但我主要是想知道是否有任何(联合国)官方文件说明这一点,或者上述哪种情况被认为是最佳做法,更有吸引力.普通程序员.
请注意,Javadoc被丢弃以减轻上面的示例代码.