Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 477
Simon Nickerson Avatar asked Aug 07 '09 07:08

Simon Nickerson


2 Answers

IMO, the problem with Java anti-patterns is that they encourage black-and-white thinking.

In reality, most anti-patterns are nuanced. For example, the linked article explains how pseudo-typedefs leads to APIs whose type signatures are too restrictive, too tied to particular implementation decisions, viral, and so on. But this is all in the context of public APIs. If you keep pseudo-typedefs out of public APIs (i.e. restrict them to a class, or maybe a module), they probably do no real harm and they may make your code more readable.

My point is that you need to understand the anti-patterns and make your own reasoned judgement about when and where to avoid them. Simply taking the position that "I will never do X because it is an anti-pattern" means that sometimes you will rule out pragmatically acceptable, or even good solutions.

like image 95
Stephen C Avatar answered Sep 28 '22 05:09

Stephen C


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.

like image 22
dfa Avatar answered Sep 28 '22 04:09

dfa