涉及幻数的全局常量的最佳实践
为了避免幻数,我总是在代码中使用常量。过去,我们曾经在无方法接口中定义常量集,现在它已成为一种反模式。
我想知道最佳实践是什么?我说的是全局常数。枚举是 Java 中存储常量的最佳选择吗?
To avoid magic numbers, I always use constants in my code. Back in the old days we used to define constant sets in a methodless interface which has now become an antipattern.
I was wondering what are the best practices? I'm talking about global constants. Is an enum the best choice for storing constants in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于幻数,其中数字实际具有含义而不仅仅是一个标签,您显然不应该使用枚举。那么旧的风格仍然是最好的。
当你只是标记某些东西时,你会使用枚举。
有时将所有全局常量放在它们自己的类中是有意义的,但我更喜欢将它们放在与它们联系最紧密的类中。这并不总是很容易确定,但归根结底,最重要的是您的代码可以工作:)
For magic numbers where the number actual has a meaning and is not just a label you obviously should not use enums. Then the old style is still the best.
When you are just labelling something you would use an enum.
Sometimes it makes sense to put all your global constants in their own class, but I prefer to put them in the class that they are most closely tied to. That is not always easy to determine, but at the end of the day the most important thing is that your code works :)
是的。枚举是最好的选择。
您将免费获得:
全部合而为一。
但是等等,还有更多。每个枚举值都可以有自己的字段和方法。它是一个丰富的常量对象,其行为允许转变为不同的形式。不仅是 toString,还有 toInt、toWhateverDestination 你需要的。
Yes it is. Enum is the best choice.
You are getting for free:
All in one.
But wait, there's some more. Every enum value can have its own fields and methods. It's a rich constant object with behavior that allows transformation into different forms. Not only toString, but toInt, toWhateverDestination you need.
枚举最适合大多数情况,但不是所有情况。有些可能最好像以前一样放在一个带有公共静态常量的特殊类中。
枚举不是最佳解决方案的示例是数学常数,例如 PI。为此创建一个枚举会使代码变得更糟。
用法:
丑陋不是吗?比较:
Enum is best for most of the case, but not everything. Some might be better put like before, that is in a special class with public static constants.
Example where enum is not the best solution is for mathematical constants, like PI. Creating an enum for that will make the code worse.
Usage:
Ugly isn't it? Compare to:
使用接口来存储常量是某种滥用接口的行为。
但使用枚举并不是适合每种情况的最佳方法。通常,一个简单的
int
或任何其他常量就足够了。定义自己的类实例(“类型安全枚举”)更加灵活,例如:Using interfaces for storing constants is some kind of abusing interfaces.
But using Enums is not the best way for each situation. Often a plain
int
or whatever else constant is sufficient. Defining own class instances ("type-safe enums") are even more flexible, for example:忘记枚举 - 现在,当 Java 中可以使用静态导入时,请将所有常量放入 REAL 类(而不是接口)中,然后使用 import static从所有其他类中导入静态成员。 。
Forget about enums - now, when static import is available in Java, put all your constants in REAL class (instead of interface) and then just import the static members from all the other ones using
import static <Package or Class>
.