'public static final' or 'private static final' with getter? 'public static final' or 'private static final' with getter? java java

'public static final' or 'private static final' with getter?


There's one reason to not use a constant directly in your code.

Assume FOO may change later on (but still stay constant), say to public static final int FOO = 10;. Shouldn't break anything as long as nobody's stupid enough to hardcode the value directly right?

No. The Java compiler will inline constants such as Foo above into the calling code, i.e. someFunc(FooClass.FOO); becomes someFunc(5);. Now if you recompile your library but not the calling code you can end up in surprising situations. That's avoided if you use a function - the JIT will still optimize it just fine, so no real performance hit there.


Since a final variable cannot be changed later if you gonna use it as a global constant just make it public no getter needed.


Getter is pointless here and most likely will be inlined by the JVM. Just stick with public constant.

The idea behind encapsulation is to protect unwanted changes of a variable and hide the internal representation. With constants it doesn't make much sense.