Constants in Java - The Anti-Pattern - DZone Java
So, to "clean up" the code he might want to implement the interface, so he doesn't need to write "packagename.Constants" everywhere, and all the constants are accessible directly.
But as soon as he implements the interface, all the constants become a part of his "Contract" (as they are public and static). This may result in adding non-required constants part of the contract of the class. This is shaking the fundamentals, and adds to confusion. There is no way in Java to stop an interface from being implemented by a class.
On the other hand, we can make the class final and hence non-extendable. Moreover we can make the constructor private hence this class is non-instantiable. Since the new class is non-instantiable, it will never break the contract. Also, if a particular constant is being used multiple times in the same class, the developer might make use of static import.
Read full article from Constants in Java - The Anti-Pattern - DZone Java
No comments:
Post a Comment