Constant Interface Anti-Pattern Clarification

The arguments against the “Constant Interface Pattern” are mainly stylistic. You can use a Constant Interface in Java if it suits your need and in fact the Java libraries include a few of these (though they are considered poor examples that shouldn’t be repeated).

The reasons why the Constant Interface is considered by many to be an “anti-pattern” are enumerated in Effective Java, 2nd Ed. Briefly, some of the reasons that this use of interfaces are discouraged include:

  • Namespace pollution. The named constants appear in the namespace of all implementing classes as well as their subclasses.

  • Interfaces should define types. In Java, most of the major types in a project should be represented by interfaces. A constant interface by its nature does not define a type.

  • Noninstantiable classes with import static. Declaring constants as static final fields in a class (rather than an interface) achieves all the same objectives as declaring them in an interface. Doing so does not create namespace pollution by the class. If desired, these constants can be used without the qualifying class name by using the import static declaration.

  • Interfaces should specify behavior. An interface is supposed to define a contract between the interface and implementing classes. Implementing the interface is supposed to say something about what the class can do. Constant interfaces do not follow this pattern.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)