“伪类型定义反模式"有什么理由吗? [英] Is there ever justification for the "pseudo-typedef antipattern"?
问题描述
我有一个相对复杂的泛型类型(比如 Map
),我在类内部使用它.(没有外部可见性;它只是一个实现细节.)我想将其隐藏在 typedef 中,但 Java 没有这样的功能.
昨天我重新发现了以下习语,并且很失望地得知它是 被认为是一种反模式.
<预><代码>我的课堂{/* 伪类型定义" */私有静态类 FooBarMap 扩展了 HashMap当类型被隐藏并且不构成库 API 的一部分时(在我的阅读中这是 Goetz 反对使用它的主要反对意见),这有什么理由吗?
真正的问题是这个习语在你的伪类型定义和你的客户端代码之间造成了高度耦合.但是由于您私下使用FooBarMap
,因此没有真正的耦合问题(它们是实现细节).
注意
现代 Java IDE 应该绝对有助于处理复杂的泛型类型.
I have a relatively complicated generic type (say Map<Long,Map<Integer,String>>
) which I use internally in a class. (There is no external visibility; it's just an implementation detail.) I would like to hide this in a typedef, but Java has no such facility.
Yesterday I rediscovered the following idiom and was disappointed to learn that it's considered an anti-pattern .
class MyClass
{
/* "Pseudo typedef" */
private static class FooBarMap extends HashMap<Long,Map<Integer,String>> { };
FooBarMap[] maps;
public FooBarMap getMapForType(int type)
{
// Actual code might be more complicated than this
return maps[type];
}
public String getDescription(int type, long fooId, int barId)
{
FooBarMap map = getMapForType(type);
return map.get(fooId).get(barId);
}
/* rest of code */
}
Can there ever be any justification for this when the type is hidden and isn't forming part of a library API (which on my reading are Goetz's main objections to using it)?
The real problem is that this idiom creates an high coupling between your pseudo typedef and your client code. However since you are using FooBarMap
privately there are no real problems of coupling (they are implementation details).
NB
A modern Java IDE should definitively helps to dealing with complicated generic types.
这篇关于“伪类型定义反模式"有什么理由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!