I thought was a good practice to put static members into an interface and inherit from that interface.
But it's a very bad idea or even more an Antipattern : Constant Interface Antipattern (see Effective Java) .
Why is it so bad?
The use of static member from another class is an implementation details and interfaces are used to abstract from implementation details.
In other words:
The use of static member causes a leakage of implementation details into many unrelated classes, because any of the defined static constant will be available to all of your classes that implement this interface.
So remember:
Interfaces are for defining contracts, not for constants.
Why do you want to declare static members into an interface?
May be to avoid putting class names in front of constants while accessing them or to group related constants .
Solutions?
Put constants into class and use static import but Very sparingly!
Use only when you require frequent access to static members from one or two classes.
If you overuse the static import feature, it can make your program unreadable and unmaintainable, you not know which class a static member comes from but used appropriately, static import can make your code more readable, by removing the boilerplate of repetition of class names.
Interesting link :
http://download.oracle.com/javase/1,5.0/docs/guide/language/static-import.html
http://www.jroller.com/ksevindik/entry/some_thoughts_about_constant_interface
http://stackoverflow.com/questions/3547792/grouping-related-constants-shared-between-classes
Nessun commento:
Posta un commento