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"; }
Java programmers commonly define constants inside their interfaces, if it makes design sense. You can do so using variables in an interface because the values will be present instantly at runtime and their values shared among all classes implementing your interface, because they are static and final.
A Java interface can contain constants. In some cases it can make sense to define constants in an interface. Especially if those constants are to be used by the classes implementing the interface, e.g. in calculations, or as parameters to some of the methods in the interface.
That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.
You declare a constant within a procedure or in the declarations section of a module, class, or structure. Class or structure-level constants are Private by default, but may also be declared as Public , Friend , Protected , or Protected Friend for the appropriate level of code access.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With