Constant-Only Interface
ID |
java.constant_only_interface |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Description
Reports interfaces that contain only field declarations (constants) and no method declarations.
Rationale
An interface that only declares constants and no methods is known as a "constant interface". This is an anti-pattern because interfaces are meant to define behavioral contracts, not to serve as constant repositories. Classes that implement such an interface pollute their public API with those constants, and the constants leak into the implementing class’s namespace unnecessarily.
// Bad -- constant interface anti-pattern
public interface StatusCodes {
int OK = 200;
int NOT_FOUND = 404;
int ERROR = 500;
}
Remediation
Move the constants into a utility class with a private constructor, or use an enum if the constants represent a finite set of related values.
// Good -- utility class
public final class StatusCodes {
public static final int OK = 200;
public static final int NOT_FOUND = 404;
public static final int ERROR = 500;
private StatusCodes() {}
}