开发者

How can I simplify hierarchical class structure resulting in chained method calls?

开发者 https://www.devze.com 2023-01-18 04:15 出处:网络
I have the following hierarchy of classes in a problem that I am working on. DiscountEvent DiscountGroup

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 i开发者_如何学Cnto 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消