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;
}
...
}
这篇关于涉及幻数的全局常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:涉及幻数的全局常量的最佳实践
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
