0

Let's say I have a class with a method that uses some static final variables as constants, but no other method in the class uses them.

For example, an AVLTree class with a balance method that uses these constants to describe balance factors for rotations

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;

Where is it best to place these constants according to Java coding conventions (e.g., Oracle's Code Conventions)?

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;    
    }

    ...
}
Josh Broadhurst
  • 407
  • 3
  • 14
  • 1
    I think it will compile down to the same thing. It's more your preference. with IDEs these days I'm not sure how much it really matters. But I would put it at the top style wise – dkatzel Nov 06 '15 at 19:08
  • 1
    If they have no purpose/meaning outside the method, then put them in the method, and the compiler will likely eliminate them entirely. If they may have purpose outside the method, even if only used by the method, then put them up front, *before* instance fields. Even though the compiler will likely still inline them, so they are unused once compiled, they are still part of the class definition and can be seen through reflection, so they do have a (very small) impact. – Andreas Nov 06 '15 at 19:14

2 Answers2

4

If you know for a fact that none of your methods now or in the future will use those variables, you can make them local variables inside the method.

However, if there's a chance that the variables may be used by some other method in the future (inside the class or by an external class), make the variables public and place them at the top.

The placement won't affect compilation but it's good practice to stay consistent with where you define your variables and methods.

Wazzymandias
  • 328
  • 2
  • 10
2

It's good practice to place all constants at top of the class.

For example, Sun's Code Convention determined this class file organization.

Ιναη ßαbαηιη
  • 3,410
  • 3
  • 20
  • 41