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;
}
...
}
这篇关于涉及幻数的全局常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:涉及幻数的全局常量的最佳实践


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01