Java 8 : When the use of Interface static methods becomes a bad practice?

标签 java interface

从 Java 8 开始,我们可以在接口(interface)中使用默认方法和静态方法。

常量接口(interface)模式是对接口(interface)的不良使用,称为常量接口(interface)反模式

>Effective Java , 第 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.

如果使用常量接口(interface)是一种不好的做法,那么什么时候使用接口(interface)静态方法就可能成为一种不好的做法?

最佳答案

常量接口(interface)的主要问题不是包含大量常量的接口(interface)。

当类实现该接口(interface)时,它们就可以更轻松地访问常量:

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 不仅在接口(interface) Foo 和它本身之间创建了一个虚假的关系(那里真的没有什么可实现的),而且常量值成为其公共(public)的一部分API。

(在 Java 5 中引入 static import 之前,这种做法更为常见。)

对于静态接口(interface)方法,实现接口(interface)真的没有意义,因为您不能以相同的方式访问它们:静态接口(interface)方法不是继承的。

关于Java 8 : When the use of Interface static methods becomes a bad practice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598776/

相关文章:

c++如何使用另一个项目中的类

java - 界面内容

Java错误=不是抽象的并且不重写抽象方法

java - 在sparkSession上注册两个同名的udf

java - 删除 xml 版本控制 + 启动节点

java - 选择不属于关系表一部分的表属性

c# - 接口(interface)不能包含字段

java - 使用 Swing 将工具栏添加到框架

java - Android Studio Java 语法配色方案

android - 波处理和 Raspberry Pi