Alex Rivera | Logout

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

Asked 2009-08-07T07:46:34.713
10

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

Edit
Report

2 Answers

3

For public interfaces I don't like to see generic types, because they have no meaning. To me seeing a method with an argument of HashMap<Long,Map<Integer,String>> is much like those C methods like foo(int, int, int, void*, int) and so on. Having a real type just makes code a lot easier to read. For a public interface it would be better to create FooBarMap that wraps HashMap<Long,Map<Integer,String>> rather than 'typedef,' but for class-internal use I see no down-side at all.

answered 2009-08-07T08:03:05.460
0

If you only use it in a small localised unit of code, the problems are small, true.

Thing is, so are the gains: your program probably won't even get textually smaller until you reference the pseudo-typedef 5+ times, which means the area it is visible in has to be non-trivial.

I probably wouldn't rewrite code that did this, but it seems a bad habit to get into.

answered 2009-08-07T08:16:43.623

Your Answer