From Java 8, we can have default methods and static methods in the interfaces.
The constant interface pattern is a poor use of interfaces known as Constant Interface Antipattern.
>Effective Java, Item 17 :
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.
If the use of constant interfaces is a bad practice, when the use of interface static methods could becomes a bad practice ?
The main problem with constant interfaces isn't the interface that contains a lot of constants.
It's when classes implement that interface just so they can access the constants easier:
public interface Foo {
public static final int CONSTANT = 1;
}
public class NotOkay implements Foo {
private int value = CONSTANT;
}
public class Okay {
private int value = Foo.CONSTANT;
}
Class NotOkay
not only creates a fake relationship between the interface Foo
and itself (there really is nothing to implement there), but the constant values become part of its public API.
(This practice was a lot more common before static import
s were introduced in Java 5.)
With static interface methods there is really no point implementing the interface because you can't access them in the same manner: static interface methods are not inherited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With