组合通用边界是反模式吗?
作为我的上一个问题的后续 具有组合通用边界的函数,例如:
<T extends Foo & Bar> void doStuff(T argument) {
//do stuff wich should only be done if arguments is both foo and bar
}
因为这不能从未指定的对象进行转换,所以您需要了解实际实现这些接口的某个对象。 在我看来,需要知道传递给 doStuff(T a) 的对象参数的具体类型违反了德米特定律。
该函数没有指定需要了解实际的类(可能有很多不同的类),而且我真的不想知道它,因为了解这个类会增加我的代码库中的依赖性。
使用这些边界是反模式吗? 如果是这样,应该如何最好地避免它?
该案例场景涉及一个指定对象是持久性的接口,而另一个指定的对象具有相关实体。 在本例中,doStuff(T a)
函数在持久化相关实体时对其进行持久化。 然而,非持久实体也可以有相关实体,但不应由 doStuff(T a)
函数处理
as a follow up on my previous question
Having a function with combined generic bounds such as:
<T extends Foo & Bar> void doStuff(T argument) {
//do stuff wich should only be done if arguments is both foo and bar
}
Because this is not castable from a unspecified object, you need to have knowledge of some object which actually implements these interfaces. it seems to me that needing to know the specific type of the object argument to pass to doStuff(T a)
is a violation of Demeter's law.
The function doesn't specify the need to know the actual class (there could be many different ones), and i really don't want to know it as knowing this class increases the dependency in my code base.
is using these bounds an anti pattern? and if so how should one best avoid it?
the case scenario involved one interface specifying the object is persistent and the other specified object having a related entity. the doStuff(T a)
function in this case persisted the related entity when it was persisted. however nonpersistent entities can also have a related entity, but should not be processed by the doStuff(T a)
function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为组合通用边界是反模式。 至少我在我的代码中对它们有一些用途。 例如,以下示例代码使用 Comparable 接口中的 CompareTo 查找集合中最大的 Number 实例:
I wouldn't consider combined generic bounds an anti-pattern. At least I've got some uses for them in my code. For instance, the following sample code finds the biggest Number instance in a collection using compareTo from the Comparable interface:
我不同意。 我不明白如何
需要更多的论证知识才能通过
,或者甚至更多,
在所有情况下,你都需要了解一些关于论证的知识,我不认为第一个案例需要比其他案例更多的知识,因为它有两个身份标识。
I disagree. I don't see how
requires any more knowledge of argument to pass then
Or even more then just
In all cases you need to know something about argument and I don't think the first cases is demanding any more knowledge then others because it has two identifiers.
反模式是铸造。
然而,花哨的泛型步骤可能会让非高级程序员感到困惑。 这些类型和方法的使用应该比它们的实现容易得多。
The anti-pattern is casting.
However, fancy generics footwork may be confusing to non-advanced programmers. Usage of such types and method should be much easier than their implementation.