Simon Nickerson Simon Nickerson - 14 days ago 7
Java Question

Is there ever justification for the "pseudo-typedef antipattern"?

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)?

dfa dfa
Answer

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.