Some time ago I have read two different books and each of them gives totally different answer for the question if it is a good pattern to define constant values in the interface (in java).
So I am curious of your opinions with some reasonable arguments.
Is it a good habit/ pattern to define constant values in interfaces in java?
Is it generally good, generally bad or it depends?
4
Item 19 of Effective Java 2nd ed. recommends the following:
If the constants are strongly tied to an existing class or interface, you should add them to the class or interface…If the constants are best viewed as members of an enumerated type, you should export them with an enum type. Otherwise, you should export the constants with a noninstantiable utility class.
public class SomeConstants {
private SomeConstants() { } // Private default constructor
public static final double WEIRD_NUMBER = 123456.7;
public static final int ANOTHER_NUMBER = 5;
}
Edit: As with all things, exceptions exist. This case (constants and some methods need to be shared by external types) might be a good argument for using an interface in this manner.
6
I use constants in interface
to have the same references when my programms have internal parameters, about all when thoses constants may change in next version,
and I use enum
otherwhere.
I have also a interface
of usual constant by default, those constants are use if no other environment parameter given by some myFile.properties
overwrite them.
Effective Java (2008) from Joshua Bloch give many tips about it.