Best practice for defining a constant - within a class or internal interface?
I have a class that only has a constant. Snippets of code:
public class CommonConstant
{
public static final String DAY = "DAY";
public static final String WEEK = "WEEK";
public static final String MONTH = "MONTH";
public static final String YEAR = "YEAR";
public static final String ACCEPTED = "accepted";
public static final String REJECTED = "rejected";
public static final String ADDED = "added";
public static final String MODIFIED = "modified";
}
Is it okay to specify constants in the class file or should it be in the interface? What is good practice?
source to share
What is a good practice
This is really good practice.
public enum EnumTest {
DAY("DAY"), WEEK("WEEK"), MONTH("MONTH"), YEAR("YEAR");
private String value;
private EnumTest(String s) {
value = s;
}
public String getValue() {
return value;
}
}
Then elsewhere
System.out.println(EnumTest.DAY.getValue()); // give you the value
or
for(EnumTest e :EnumTest.values()){ //values return an array of enum values
System.out.println(e);
}
source to share
Since constants are implementation specific, you must put them in a class with a private constructor, or alternatively an enum. Joshua Bloch in Effective Java 2nd Edition discourages the use of "persistent interfaces".
Bloch says that interfaces should only be used to define types, and that when a class implements an interface, that one serves as a type to refer to an instance - it is inappropriate to use the interface for any other purpose. As mentioned earlier, constants are implemented
and more relatively persistent interfaces
if a class is changed in a future version so that it is no longer needed to use constants, it must still implement the interface to ensure binary compatibility. If a non-final class implements an interface constant, all of its subclasses will have a polluted namespace over the constants in the interface
BlocHquoted :)
HTH, Carlo
source to share