涉及幻数的全局常量的最佳实践 [英] Best practice for global constants involving magic numbers

查看:58
本文介绍了涉及幻数的全局常量的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免幻数,我总是在我的代码中使用常量.回到过去,我们过去常常在无方法接口中定义常量集,现在它已成为一种反模式.

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;
  }
  ...
}

这篇关于涉及幻数的全局常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆