gpt4 book ai didi

java - 为什么坚持接口(interface)的所有实现都扩展基类?

转载 作者:IT老高 更新时间:2023-10-28 21:19:34 26 4
gpt4 key购买 nike

我只是在 GitHub 上查看 Java Hamcrest 代码,并注意到他们采用了一种看起来不直观且尴尬的策略,但这让我想知道我是否遗漏了什么。

我注意到在 HamCrest API 中有一个接口(interface) Matcher 和一个抽象类 BaseMatcher 。 Matcher 接口(interface)用这个 javadoc 声明了这个方法:

    /**
* This method simply acts a friendly reminder not to implement Matcher directly and
* instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore
* compile errors .
*
* @see Matcher for reasons why.
* @see BaseMatcher
* @deprecated to make
*/
@Deprecated
void _dont_implement_Matcher___instead_extend_BaseMatcher_();

那么在BaseMatcher中,这个方法实现如下:

    /**
* @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_()
*/
@Override
@Deprecated
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}

诚然,这既有效又可爱(而且非常尴尬)。但如果目的是让每个实现 Matcher 的类也扩展 BaseMatcher,那为什么还要使用接口(interface)呢?为什么不首先让 Matcher 成为一个抽象类并让所有其他匹配器扩展它呢?像 Hamcrest 那样做有什么好处吗?或者这是不良做法的一个很好的例子?

编辑

一些很好的答案,但为了寻找更多细节,我提供了赏金。我认为向后/二进制兼容性问题是最好的答案。但是,我希望看到更多关于兼容性问题的详细说明,最好是使用一些代码示例(最好是在 Java 中)。此外,“向后”兼容性和“二进制”兼容性之间是否存在细微差别?

进一步编辑

2014 年 1 月 7 日 -- pigroxalot 在下面提供了答案,链接到 this comment on Reddit 由 HamCrest 的作者编写。我鼓励大家阅读它,如果你觉得它内容丰富,请点赞 pigroxalot 的答案。

甚至进一步编辑

2017 年 12 月 12 日 - pigroxalot 的答案以某种方式被删除,不知道这是怎么发生的。太糟糕了......那个简单的链接非常有用。

最佳答案

git log 有这个条目,从 2006 年 12 月(初次 checkin 后大约 9 个月)开始:

Added abstract BaseMatcher class that all Matchers should extend. This allows for future API compatability [sic] as the Matcher interface evolves.

我还没有试图弄清楚细节。但是随着系统的发展保持兼容性和连续性是一个难题。这确实意味着,如果您从头开始设计整个事物,有时您最终会得到一个您永远不会创建的设计。

关于java - 为什么坚持接口(interface)的所有实现都扩展基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20712782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com