Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use nested genericized collections or custom intermediate classes?

Tags:

java

oop

generics

Before the introduction to generics to the Java language I would have written classes encapsulating collections-of-collections-of-collections. For example:

class Account {
   private Map tradesByRegion; //KEY=Region, VALUE=TradeCollection
}

class TradeCollection {
   private Map tradesByInstrument; //KEY=Instrument, Value=Trade
}

Of course, with generics, I can just do:

class Account {
   private Map<Region, Map<Instrument, Trade>> trades;
}

I tend to now opt for option #2 (over a generified version of option #1) because this means I don't end up with a proliferation of classes that exist solely for the purpose of wrapping a collection. But I have a nagging feeling that this is bad design (e.g. how many nested collections should I use before declaring new classes). Opinions?

like image 883
oxbow_lakes Avatar asked Mar 08 '09 17:03

oxbow_lakes


2 Answers

2 is better because:

  • Less code accomplishes the same effect (better, actually, as in #1 some of your type information exists only in comments)
  • It's completely clear what's going on.
  • Your type errors will be caught at compile time.

What is there to recommend 1? admittedly the Map< Integer , < Map < String, < Map< ... generics are a bit hard to get used to, but to my eye it's much easier to understand than code with maps, and lists of maps, and maps of lists of maps, and custom objects full of lists of maps.

like image 111
Steve B. Avatar answered Sep 18 '22 01:09

Steve B.


Combination of the two. While you can use generics to replace custom classes, you still will want to use a class to encapsulate your concepts. If you're just passing maps of maps of maps of lists to everything, who controls what you can add? who controls what you can remove?

For holding the data, generics is a great thing. But you still want methods to validate when you add a trade, or add an account, and without some kind of class wrapping your collections, nobody controls that.

like image 45
John Gardner Avatar answered Sep 19 '22 01:09

John Gardner