Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice to define constant - inside class or inside interface? [closed]

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 ?

like image 759
unknown Avatar asked Feb 12 '23 01:02

unknown


2 Answers

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

like image 75
Carlo Bertuccini Avatar answered Feb 14 '23 15:02

Carlo Bertuccini


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);
}
like image 41
SparkOn Avatar answered Feb 14 '23 13:02

SparkOn