涉及幻数的全局常量的最佳实践

2022-01-24 00:00:00 coding-style constants 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.

我想知道最佳做法是什么?我说的是全局常量.枚举是在 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;
  }
  ...
}

相关文章