Using constants in an interface

Metadata

ID: java-best-practices/constants-in-interfaces

Language: Java

Severity: Notice

Category: Best Practices

Description

Java interfaces are designed to define types and should not be cluttered with implementation details like constants. Constants are better suited to be placed within classes or enums.

If the constants fit into an enumerated type, it is recommended to export them using an enum. This keeps the code clean and follows the intended purpose of enums.

For cases where constants are not related to an enumerated type, a more suitable approach would be to use a utility class. This follows the principle advocated in Effective Java, which promotes the use of interfaces for defining types only.

By following these guidelines, your codebase will be well-organized, easier to maintain, and aligned with industry best practices.

Non-Compliant Code Examples

public interface FooInterface {
    public static final int CONST1 = 1;

    int anyMethod(); // we have a method here
}
public interface FooInterface {
    public static final int CONST1 = 1; // no field allowed in interface
    static final int CONST2 = 1;        // no field allowed in interface
    final int CONST3 = 1;               // no field allowed in interface
    int CONST4 = 1;                     // no field allowed in interface
}

Compliant Code Examples

public interface Foo {
    void doSomething();

    int calculate(int a, int b);

    String getName();
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis