![]() ![]() ![]() Here are the drawbacks of using the constant interface pattern, according to Joshua Bloch (Bloch, Joshua, Effective Java, 2nd Edition, p. Words, use it when you require frequent access to static members from Or to abuse inheritance (the Constant Interface Antipattern). When you'd otherwise be tempted to declare local copies of constants, "So when should you use static import? Very sparingly! Only use it Since then constants in interfaces have been abandoned in favor of static imports, which are also no perfect and classes of constants. Annotation gives you the ability to provide additional metadata alongside a Java entity (such as classes, interfaces, fields and methods). In fact this is something we used to do in the very first versions of Java, many years back. If someone managed to give you a few good cases where one would use fields in interfaces as opposed to many other ways to satisfy the same design requirement, it would automatically justify using constants in interfaces. They should not be used to export constants.īottom line, there is always a better way to define constants than in an interface. In summary, interfaces should be used only to define types. More about it in Effective Java Item #19 "Use interfaces only to define types", which concludes with: You can also declare them in an enum when they are an enumeration (colours for example). If you just want to group a certain number of constants together, you can define them in a final class: final class Constants //non instantiable ![]() And if only one class is really tied to the constant, you should declare it there. For instance, a human and a parrot can both whistle however, it would not make sense to represent Human s and Parrot s as subclasses of a Whistler class. If it makes sense that a number of implementations will share a constant, you can define it in an abstract class that will be used as a base class for the hierarchy. Overview Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. An interface is meant to define a contract, and constants are an implementation detail. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |