The Constant Interface Antipattern – How not to define constants

When working in applications that utilize a lot of variables I often come across interfaces containing nothing but constants. Instead of creating a class containing the constants the developers choose to define them in an interface that can be implemented by a class so that constants don’t need to be qualified to a class in the code. This is so widespread that it has been termed the Constant Interface Antipattern. To ease users into correctly defining and using interfaces Java introduced Static Import in version 1.5.

To help illustrate why people choose to use interfaces to define constants lets have a look at an example. Lets assume we have defined our constants in the following interface MyConstants.

public interface MyConstants {
    public static final String PASS= "pass";
    public static final String FAIL = "fail";
}

To use the constants one would have their class implement the interface:

public class BadConstants implements MyConstants {
    private void outputResults() {
        System.out.println("FAIL Constant is " + FAIL);
        System.out.println("PASS Constant is " + PASS);
    }
}

As can be seen in the example the reason people prefer to use this method is that they do not have to qualify the constant by instead using:

System.out.println("FAIL Constant is " + MyConstants.FAIL);

To make it easier for coders to write good code Java introduced the Static Import feature in 1.5. What this does is allow us developers to import static properties into the current class’s namespace effectively allowing you to not qualify the constants. This is down by use of the import static statement where you can import a single constant or all constants of a class.

import static com.example.MyConstants.PASS;
import static com.example.MyConstants.*;

To put it simply don’t define constants in an interface, instead create them properly in their own classes and if you really don’t want to qualify them then utilize static import to import the constants into your class.

References

Comments & Questions

Add Your Comment