Java class 中方法的静态最终常量的位置
Location of static final constants for method in Java class
假设我有一个 class 方法,它使用一些静态最终变量作为常量,但 class 中没有其他方法使用它们。
例如,具有平衡方法的 AVLTree class 使用这些常量来描述旋转的平衡因子
private static final int L_HEAVY = 2;
private static final int LL_HEAVY = 1;
private static final int R_HEAVY = -2;
private static final int RR_HEAVY = -1;
根据 Java 编码约定(例如 Oracle 的代码约定),将这些常量放在什么地方最好?
public class AVLTree {
private Node root;
// (1) Here, among members, right after class declaration ?
public AVLTree() {
root = null;
}
...
// (2) Here, just above the method that uses them?
private Node balance(Node node) {
// (3) Here, inside the method that uses them?
if (height(node.left) - height(node.right) == L_HEAVY) {
if (height(node.left.left) - height(node.left.right) == LL_HEAVY) {
...
}
}
if (height(node.left) - height(node.right) == R_HEAVY) {
if (height(node.right.left) - height(node.right.right) == RR_HEAVY) {
...
}
}
return node;
}
...
}
假设我有一个 class 方法,它使用一些静态最终变量作为常量,但 class 中没有其他方法使用它们。
例如,具有平衡方法的 AVLTree class 使用这些常量来描述旋转的平衡因子
private static final int L_HEAVY = 2;
private static final int LL_HEAVY = 1;
private static final int R_HEAVY = -2;
private static final int RR_HEAVY = -1;
根据 Java 编码约定(例如 Oracle 的代码约定),将这些常量放在什么地方最好?
public class AVLTree {
private Node root;
// (1) Here, among members, right after class declaration ?
public AVLTree() {
root = null;
}
...
// (2) Here, just above the method that uses them?
private Node balance(Node node) {
// (3) Here, inside the method that uses them?
if (height(node.left) - height(node.right) == L_HEAVY) {
if (height(node.left.left) - height(node.left.right) == LL_HEAVY) {
...
}
}
if (height(node.left) - height(node.right) == R_HEAVY) {
if (height(node.right.left) - height(node.right.right) == RR_HEAVY) {
...
}
}
return node;
}
...
}