java 常量集合应该放在类还是接口中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1372991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should a collection of constants be placed in a class or interface?
提问by DaveJohnston
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).
如果我有一组要集中声明的静态常量,以便在将它们放入类或接口 (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";
}
or
或者
public interface ErrorCodes {
public static final String ERROR_1 = "-1";
public static final String ERROR_2 = "-2";
}
采纳答案by Joachim Sauer
If they have strong connections, then I'd put them in an enum:
如果他们有很强的联系,那么我会把他们放在一个枚举中:
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;
}
}
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()).
优点是您可以在代码中具有类型安全性,并且可以轻松添加基于 id 的查找(通过HashMap<String,Error>在构造函数中构建 a或简单地循环values())。
回答by Andrey Adamovich
Some people consider constant-interface an anti-pattern (http://en.wikipedia.org/wiki/Constant_interface) .
有些人认为常量接口是一种反模式(http://en.wikipedia.org/wiki/Constant_interface)。
回答by Tomas Aschan
You should do it in a class.
你应该在课堂上做。
An Interface is a description of available methods, properties etc that class users can access - by implementing an interface, you guarantee that the members declared in the interface are available to the user.
接口是对类用户可以访问的可用方法、属性等的描述 - 通过实现接口,您可以保证在接口中声明的成员对用户可用。
A class, on the other hand, is a description of an object or (if you're not toohard on the OO principles...) a placeholder for static members. I personally find it very useful in some projects to store away a bunch of constants in a Settingsclass, so I don't have to look around in the entire project for the definitions. I think this approach is what you're after, too.
另一方面,类是对对象的描述,或者(如果您对 OO 原则不太严格的话……)是静态成员的占位符。我个人发现在某些项目中将一堆常量存储在一个Settings类中非常有用,因此我不必在整个项目中四处寻找定义。我认为这种方法也是你所追求的。
回答by gustafc
This has been discussed before:
The reason why you don't want the constants in an interface is that it entices client classes to "implement" that interface (in order to access the constants without prefixing them with the interface name). You shouldn't, though - the interface isn't actually an interface to the object's capabilities, but a compile-time convenience ingrained in the class' external type.
您不希望接口中的常量的原因是它诱使客户端类“实现”该接口(以便访问常量而不用接口名称作为前缀)。但是,您不应该这样做 - 接口实际上不是对象功能的接口,而是在类的外部类型中根深蒂固的编译时便利。
There was a time when the "constant interface" was very convenient, but it has always been "wrong" and not even laziness is an excuse to use it now that we have import staticstatements.
曾经有一段时间“常量接口”非常方便,但它一直是“错误的”,现在我们有了import static语句,甚至懒惰也不是使用它的借口。
Edit:Although I must agree that for the scenario presented in your question, enums are more appropriate.
编辑:虽然我必须同意,对于您问题中提出的场景,枚举更合适。
回答by VonC
The use of static importshould be considered here (for importing constants defined in a class), or type-safe Enum.
此处应考虑使用静态导入(用于导入类中定义的常量),或类型安全的 Enum。
从常量接口
Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data.
As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class.
在 Java 早期,将常量放在接口中是一种流行的技术,但现在许多人认为这是对接口的一种令人反感的使用,因为接口应该处理对象提供的服务,而不是它的数据。
同样,类使用的常量通常是实现细节,但将它们放在接口中会将它们提升为类的公共 API。
回答by Billy Bob Bain
You should put them on the class with a private constructor.
您应该将它们放在带有私有构造函数的类中。
public class ErrorCodes {
private ErrorCodes() {} // prevents instantiation
public static final String ERROR_1 = "-1";
public static final String ERROR_2 = "-2";
}
}
Or better yet, use a typesafe enum.
或者更好的是,使用类型安全的枚举。
回答by grkvlt
I recommend a combination of static imports and interfaces for constants.
我推荐静态导入和常量接口的组合。
If a Java interface has constant field declarations, bear in mind that these are implicitlypublic, static and final (see the Java Language Specification, Section 9.3.) You can therefore always omit these modifiers, leaving only the type, and your constant interface would look like this:
如果 Java 接口具有常量字段声明,请记住它们是隐式的public、static 和 final(请参阅 Java 语言规范,第 9.3 节)。因此,您始终可以省略这些修饰符,只保留类型,并且您的常量接口将看起来像这样:
public interface Constants {
int AGE = 0x23;
String NAME = "Andrew";
boolean IGNORE = true;
}
This should, of course, onlyever be used as follows:
当然,这应该只用于如下用途:
import static Constants.*;
public Whatever {
public String method() {
return String.format("%s is %d%c", NAME, AGE, IGNORE ? '?' : '!');
}
}
I have no issues using this style in my production code, and feel it leads to a very neat, compact constants collection, and can cope with various types of constant, which an enum couldn't, as well as being able to be extended if requred, unlike an enum.
我在我的生产代码中使用这种风格没有任何问题,并且觉得它会导致一个非常整洁、紧凑的常量集合,并且可以处理枚举不能处理的各种类型的常量,并且能够在以下情况下进行扩展需要,与枚举不同。
Another possibility, which not everyone will approve of, is to nest interfaces (or even enum types) in your parent interface, allowing you to group your constants. This :
另一种并非所有人都会同意的可能性是在您的父接口中嵌套接口(甚至枚举类型),从而允许您对常量进行分组。这 :
interface MoreConstants {
int MAGIC = 0xCAFEBABE;
interface PROPERTIES {
String NAME = "name";
}
enum ERRORS {
ON_FIRE, ASLEEP, BROKEN, UNSURE;
}
}
and access them like this, assuming a static import of the MoreConstantsinterface:
并像这样访问它们,假设MoreConstants接口的静态导入:
if (!PROPERTIES.NAME.equals(value)) {
return ERRORS.UNSURE;
}
Of course, these interfaces should never be implemented, which I would consider bad practice. The only way to ensure this, however, is strict code reviews...
当然,这些接口不应该被实现,我认为这是不好的做法。然而,确保这一点的唯一方法是严格的代码......
回答by Dakshin Rajavel
Using Interface for constants is a good practice. But you do not want to implement that interface to use the constants. But use static import as below.
对常量使用接口是一个很好的做法。但是您不想实现该接口以使用常量。但是使用静态导入如下。
package com.data.job.spark;
public interface Constants {
/** base api url string literal. */
public static final String BASE_API_URL = "/api/v1";
/** message string literal. */
public static final String MESSAGE = "message";
/** exception string literal. */
public static final String EXCEPTION = "exception";
}
=================================
import static com.data.job.spark.Constants.EXCEPTION;
@Component("user360ToScyllaDbLoader")
public class TestConstants implements Serializable{
private static final long serialVersionUID = 1L;
}
回答by Rakesh Prajapati
Always use Interface to define only contract and Class to define implementation state (variable and constant) and behavior (method implementation)
始终使用 Interface 只定义 contract 和 Class 来定义实现状态(变量和常量)和行为(方法实现)
Define Constants in Interface or Class
Read this article which explains advantages of defining constants in the class vs interface
阅读这篇文章,它解释了在类与接口中定义常量的优点
回答by Rakesh Prajapati
I personally feel that the constants should be defined in a class for the same reasons as described here above. Especially because some developers use these constants by implementing the interface in the class that wants to use them. When that interface contains a lot of constants you do not want to look at the javadoc of that specific class anymore because it is littered with descriptions of constants that are probably not even used by that class.
我个人认为,出于与上文所述相同的原因,应该在类中定义常量。特别是因为一些开发人员通过在想要使用它们的类中实现接口来使用这些常量。当该接口包含大量常量时,您不想再查看该特定类的 javadoc,因为它充斥着对该类甚至可能不使用的常量的描述。

