Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a collection of constants be placed in a class or interface?

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"; } 
like image 299
DaveJohnston Avatar asked Sep 03 '09 11:09

DaveJohnston


People also ask

Should constants be in interface or class?

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.

Can I use interface for constants?

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.

Why constants should not be defined in interfaces?

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.

Where is the best place to declare constants?

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.


1 Answers

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()).

like image 167
Joachim Sauer Avatar answered Oct 01 '22 20:10

Joachim Sauer