views:

42

answers:

2

I have the following hierarchy of classes in a problem that I am working on.

DiscountEvent
  DiscountGroup
    ProductFamily
      Product

where each class contains a collection of next one (e.g. DiscountEvent contains a collection of DiscountGroups, etc)

This kind of a somewhat deep hierarchy results in many chained calls from the higher modules. For example, while reading product data from the database into this class hierarchy I have chains of calls and similar AddProduct methods.

class DiscountEvent{
  Dictionary<int, DiscountGroup> DiscountGroups;
  public void AddProduct(ProductInfo info){
    DiscountGroups[info.groupId].AddProduct(info);
  }
  ...
}
class DiscountGroup{
  Dictionary<int, productFamily> productFamilies;
  public void AddProduct(ProductInfo info){
    productFamilies[info.familyId].AddProduct(info);
  }
  ...
}
...

Similar add methods all the way to the leaf class. Can you think of any way to simplify this kind of a hierarchical class structure?

A: 

Most modern ORM could solve this problem for you.

You can't actually simplify your "hierarchy" because it based on real-life abstractions, but you can simplify your life eliminating manual child's populations.

In this case you still need all child collections (because this is part of your domain logic or data access layer), but all this complexity (with populating them) would hide by ORB implementation.

Sergey Teplyakov
A: 

One idea would be to use a form of the Serializer Pattern...because you are 'deserializing' from a database.

That is, you might have a DiscountEventReader class into which you pass the database connection - and it might call other reader classes to create the contained object instances.

This has the advantage that, for example, a ProductFamilyReader could read (and potentially cache) multiple database rows, adding multiple Product instances to the parent container without traversing the entire hierarchy of 'addProduct' calls for each new object.

sje397