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";
}
or
public interface ErrorCodes {
public static final String ERROR_1 = "-1";
public static final String ERROR_2 = "-2";
}
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()
).