Best practice for global constants involving magic numbers(涉及幻数的全局常量的最佳实践)
问题描述
为了避免幻数,我总是在我的代码中使用常量.回到过去,我们过去常常在无方法接口中定义常量集,现在它已成为一种反模式.
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.
我想知道最佳做法是什么?我说的是全局常量.枚举是在 Java 中存储常量的最佳选择吗?
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?
推荐答案
使用接口存储常量是一种滥用接口.
Using interfaces for storing constants is some kind of abusing interfaces.
但使用枚举并不是每种情况的最佳方式.通常一个普通的 int
或任何其他常量就足够了.定义自己的类实例(类型安全的枚举")更加灵活,例如:
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:
public abstract class MyConst {
public static final MyConst FOO = new MyConst("foo") {
public void doSomething() {
...
}
};
public static final MyConst BAR = new MyConst("bar") {
public void doSomething() {
...
}
};
protected abstract void doSomething();
private final String id;
private MyConst(String id) {
this.id = id;
}
public String toString() {
return id;
}
...
}
这篇关于涉及幻数的全局常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:涉及幻数的全局常量的最佳实践


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01