应该在类或接口中放置常量的集合吗? [英] Should a collection of constants be placed in a class or interface?

查看:231
本文介绍了应该在类或接口中放置常量的集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个静态常量的集合,我想集中声明,以便它们可以在各种项目之间共享,如果它们放在一个类或接口(Java)。

If I have a collection of static constants that I want to declare centrally so that they can be shared among various projects should they be put in a class or interface (Java).

在过去,我已经看到他们大部分放在一个类,但我开始认为,因为类不会,不应该实例化,也许他们会更好的一个接口,但再次的接口不应该实现任何类。例如

In the past I have seen them mostly put in a class but I started thinking that since the class will not and should not be instantiated maybe they would be better in an interface, but then again the interface should not be implemented by any classes. e.g.

public class ErrorCodes {
    public static final String ERROR_1 = "-1";
    public static final String ERROR_2 = "-2";
}

public interface ErrorCodes {
    public static final String ERROR_1 = "-1";
    public static final String ERROR_2 = "-2";
}


推荐答案

public enum Error {
  ERROR_1("-1", "foo went wrong"),
  ERROR_2("-2", "bar went wrong");

  private final String id;
  private final String message;

  Error(String id, String message) {
    this.id=id;
    this.message=message;
  }

  public String getId() {
    return id;
  }

  public String getMessage() {
    return message;
  }
}

优点是您可以在代码,你可以很容易地添加基于id的查找(通过在构造函数中构建一个 HashMap< String,Error> 或者简单地循环 ())。

The advantage is that you can have type safety in your code and that you can easily add id-based lookup (either by building a HashMap<String,Error> in the constructor or by simply looping over values()).

这篇关于应该在类或接口中放置常量的集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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