Defining constants in an interface | Java Deep
What is the drawback of defining constants in an interface then? It may accidentally be implemented and this is against the nature of an interface to deliver implementation. While I can not argue with the first part of the statement the nature of interfaces are not that solid. What about Java8? There can be static methods in an interface, and default method implementations. You may like it or not but the direction Java currently goes with interfaces is more towards the practical way. Using a pattern that defines constants in an interface to import it instead of "implementing" is directly this way.
As a summary, my suggestion is to avoid using the interface pattern as defined in "Effective Java". Never implement an interface in any of your classes only to get access to the constants defined in the class, unless the constants are inherent part of the definition of the class and not only the part of the implementation. On the other hand I see no significant danger to define a constants only interface and import it into your class and use the constants.
Next week I will write about an extended pattern using interfaces to define constants that avoids the possibility to accidentally "implement" them.
Read full article from Defining constants in an interface | Java Deep
No comments:
Post a Comment