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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With