Suppose you need to define a class which all it does is hold constants.
public static final String SOME_CONST = \"SOME_VALUE\";
What is the
One of the disadvantage of private constructor is the exists of method could never be tested.
Enum by the nature concept good to apply in specific domain type, apply it to decentralized constants looks not good enough
The concept of Enum is "Enumerations are sets of closely related items".
Extend/implement a constant interface is a bad practice, it is hard to think about requirement to extend a immutable constant instead of referring to it directly.
If apply quality tool like SonarSource, there are rules force developer to drop constant interface, this is a awkward thing as a lot of projects enjoy the constant interface and rarely to see "extend" things happen on constant interfaces
Use a final class. for simplicity you may then use a static import to reuse your values in another class
public final class MyValues {
public static final String VALUE1 = "foo";
public static final String VALUE2 = "bar";
}
in another class :
import static MyValues.*
//...
if(variable.equals(VALUE1)){
//...
}
enum
s are fine. IIRC, one item in effective Java (2nd Ed) has enum
constants enumerating standard options implementing a [Java keyword] interface
for any value.
My preference is to use a [Java keyword] interface
over a final class
for constants. You implicitly get the public static final
. Some people will argue that an interface
allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.
Which looks better?
public final class SomeStuff {
private SomeStuff() {
throw new Error();
}
public static final String SOME_CONST = "Some value or another, I don't know.";
}
Or:
public interface SomeStuff {
String SOME_CONST = "Some value or another, I don't know.";
}
Or 4. Put them in the class that contains the logic that uses the constants the most
... sorry, couldn't resist ;-)