Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just read somewhere that having an interface with common project constants is bad practice and also known as the Constant Interface Anti-Pattern. If I understood this correctly, the reason provided was that once implemented, the class would expose these constants to the public.

Well, I don't understand the need for 'implementing' in the first place. Isn't it possible to just use these static constants directly? So why do I have to go through the trouble of import static when I can do something like:

interface Constants {
    public static final int FOO_1 = 1;
    public static final int FOO_2 = 2;
}

public class Test {
    public static void main(String[] args) {
        System.out.println(Constants.FOO_2);
    }
}

I would appreciate any guidance to help me understand this a bit more.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
291 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...