Member-only story
Effective Java! Use Interfaces Only to Define Types
The purpose of interfaces is to define a type. When a class implements an interface that should tell the user of the class something about what that class can do. If we are abusing interfaces for other purposes that is an inappropriate use of an interface. That’s basically the whole of the content of this chapter. So if the interfaces is not being used to define a type what is it being used for? The most common use case is the Constant Interface Anti-Pattern. It looks something like this:
// Antipattern
public interface PhysicalConstants {
static final double AVOGAROS_NUMBER = 6.022_140_857e23;
static final double ELECTRON_MASS = 9.109_383_56e-31;
}
When a class implements an interface like the above what does that tell us about that class? Really nothing. It’s implementing it because it want’s access to those constants but the consumers of the class don’t need to know that. What it can also do is cause the consumers of your class to become dependent on those constants which locks you as the implementer from being able to remove these constants. If the constants aren’t part of the value that is provided by your class we shouldn’t be exposing them to our consumers like this interface does. So if we aren’t to do this what are we to do?
public final class PhysicalConstants {
private PhysicalConstants() { }
public static final double AVOGAROS_NUMBER = 6.022_140_857e23;
public static final double ELECTRON_MASS = 9.109_383_56e-31;
}