Reputation: 1759
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 ?
Upvotes: 10
Views: 2764
Reputation: 38152
when the use of interface static methods could becomes a bad practice ?
I was told by experts (I think it was by Angelika Langer and Klaus Kreft on a Java User Group event), that when you have a few static methods then it's usually OK to have them in the interface (see Stream), but if there are many of them then it's better to have them in a utility class (see Collectors). Otherwise it would become hard to see the actual methods of the interface.
This seems to make sense and is a good rule of thumb to stick with.
Upvotes: 5
Reputation: 49804
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.
Upvotes: 9