While coding some custom stream reader for a script result where quite a lot of constants were present in the class (mainly for expected tags and keywords), I was wondering if there was any kind of standards, conventions or best practice for where to put constants (read here static final
fields) inside a class?
More specifically, is it considered best to put every constant in the top of the class, or to group them up in the area of the class where they are useful, and group the commons at the top?
By putting everything in the top, it seems to me that this might be easier to find everything you're looking for at the same place, but it can get overwhelming if this area is getting bigger:
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!");
}
}
By grouping them up, it makes more sense to the constants that are only used in specific areas of the class, but it may break the nice symmetrical effect grouping by types adds to a class, and might make it look messy:
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!");
}
}
Output:
Test#constructor = Hello world!
Test#method1 = Hello world!
Test#method2 = Hello world!
I know this might be the subjective kind of question, but I'm mainly interested in finding out if there is any (un)official document stating this, or which of the above scenarios is considered best practice and more appealing to work with for the average programmer.
Take note that the Javadoc was discarded to lighten up the above example code.