I have a class which has only constant. Code snippets is :
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 good practice to specify constants in class file or it should be in an interface ? What is good practice ?
Since constants concerns implementation you should put them into a class with private constructor or, alternatively, an enum. Joshua Bloch in Effective Java 2nd edition discourage the use of "constant interfaces".
Bloch say that interfaces should be used only to define types and that when a class implements an interface this one serves as a type to refer to the instance -- it is inappropriate to use an interface for any other purpose. As said before, constants are implementation
and more concerning constant interfaces
if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface
BlocHquoted :)
HTH, Carlo
What is a good practice
This is actually a 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 in somewhere else
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);
}
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