涉及魔数的全局常量的最佳实践 [英] Best practice for global constants involving magic numbers
问题描述
为了避免幻数,我总是在我的代码中使用常量。回到过去,我们习惯于在无方法接口中定义常量集,现在已经成为反模式。
我想知道最好的做法是什么?我在谈论全局常量。
使用接口来存储常量是某种滥用的接口。 / p>
但是使用枚举不是每种情况的最佳方法。通常一个简单的 int
或任何其他常量是足够的。定义自己的类实例(类型安全枚举)甚至更灵活,例如:
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;
}
...
}
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?
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:
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;
}
...
}
这篇关于涉及魔数的全局常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!