Do we really need static final constants in Java?
Assume I have the following code:
public class Test {
public static final int A = 1234;
public static int getA()
{
return 1234;
}
}
Can you please compare the following two cases in terms of efficiency?
-
Test.A -
Test.getA()
Assuming a JIT compiler, there should be no noticeable difference in efficiency – at least not enough to make a significant difference in the execution speed of your application.
There is a noticeable gain in flexibility, though: encapsulating the value in a method is nearly always good, because it lets you change the way the value is calculate later.
A notable exception to this rule is pure constants, say, from the world of mathematics: it does not make much sense to encapsulate access to
Math.PI, because there is no chance that the value of this fundamental constant is going to change, prompting a need to switch the method the value is obtained in your program.