4

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 ?

unknown
  • 4,859
  • 10
  • 44
  • 62
  • 6
    Probably in enum! – Am_I_Helpful Sep 13 '14 at 10:19
  • 2
    Have a look at this question, I think it's exactly what you want: http://stackoverflow.com/questions/1372991/should-a-collection-of-constants-be-placed-in-a-class-or-interface – Bono Sep 13 '14 at 10:20
  • An Interface defines required behavior for arbitrary classes -- if the constants relate to the required Interface behavior, put the constants there! – ErstwhileIII Sep 13 '14 at 15:29

2 Answers2

4

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

Carlo Bertuccini
  • 19,615
  • 3
  • 28
  • 39
4

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);
}
SparkOn
  • 8,806
  • 4
  • 29
  • 34