Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map anti-pattern?

Edit: I've gotten a couple of answers that say what I already said in the question. What I am really interested in is finding corroborating reference material.


I am looking at a code sample that more or less follows this pattern:

Map<String, List> getListsFromTheDB() {
  Map<String, List> lists = new HashMap<String, List>();

  //each list contains a different type of object
  lists.put("xList", queryForListOfXItems());
  lists.put("yList", queryForListOfYItems());

  return lists;
}

void updateLists() {
  Map<String, List> lists = getListsFromTheDB();
  doSomethingWith(lists.get("xList"));
  doSomethingWith(lists.get("yList"));
}

My feeling is that this is an anti-pattern. What the coder should have done is create a class which can be returned, like this:

class Result {
  private final List<X> xList;
  private final List<Y> yList;

  public Result(xList, yList) {
    this.xList = xList;
    this.yList = yList;
  }

  public List<X> getXList() { xList; }
  public List<Y> getYList() { return yList; }
}

This would be more type-safe, avoid over-generalizing a very specific problem, and be less prone to errors at runtime.

Can anyone point me to any authoritative reference material which specifies that you should avoid this kind of pattern? Or, alternately, if it's actually a good pattern, please give justification.

like image 986
RMorrisey Avatar asked Sep 30 '10 00:09

RMorrisey


People also ask

What is anti-pattern in Java?

In software, anti-pattern is a term that describes how NOT to solve recurring problems in your code. Anti-patterns are considered bad software design, and are usually ineffective or obscure fixes. They generally also add "technical debt" - which is code you have to come back and fix properly later.

How do you identify anti-patterns?

In an organization, there are three main opportunities to identify anti-patterns: During design reviews, during code reviews and during refactoring of legacy code. Design reviews are a great opportunity to find anti-patterns.

What is the difference between pattern and anti-pattern?

An anti-pattern is the evil twin of a good design pattern. A good design pattern is a reusable requirement, design, or implementation that solves hard problems in a standard way, which is well designed, well documented, easy to maintain, and easy to extend.

Does map throw exception if key not found?

Map[key] returns null if key is not in the map. It could instead throw an exception, consistent with collections such as List and Queue.


1 Answers

I think the point is the number of Lists is fixed. Since you ensure the code uses 2 lists, the map is a little bit over-generalizing.

So 'class Result' is better I think.

like image 89
卢声远 Shengyuan Lu Avatar answered Oct 18 '22 14:10

卢声远 Shengyuan Lu