使用getter进行'public static final'或'private static final'? [英] 'public static final' or 'private static final' with getter?
问题描述
在Java中,它教导变量应保持私有以实现更好的封装,但静态常量呢?这个:
In Java, it's taught that variables should be kept private to enable better encapsulation, but what about static constants? This:
public static final int FOO = 5;
结果与此相当:
private static final int FOO = 5;
...
public static getFoo() { return FOO; }
但哪种做法更好?
推荐答案
有一个原因是不能在代码中直接使用常量。
There's one reason to not use a constant directly in your code.
假设FOO可能会在稍后更改(但仍保持不变),说 public static final int FOO = 10;
。只要没有人愚蠢直接硬编码这个值,不应该破坏任何东西吗?
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?
没有。 Java编译器会将诸如Foo之类的常量内联到调用代码中,即 someFunc(FooClass.FOO);
变为 someFunc(5);
。现在,如果您重新编译库而不是调用代码,则最终会出现令人惊讶的情况。如果你使用一个函数就可以避免这种情况 - JIT仍然可以很好地优化它,所以没有真正的性能。
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.
这篇关于使用getter进行'public static final'或'private static final'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!