How do you improve this design with chained AddX type of methods to construct object hierarchy from database?
Currently, I am dealing with multiple layers of composition in my application. We read data from database for ProductLocations
and put them into a Solver
object. In another query we read multiple SalesActivities
connected to product locations which needs to be placed in an object deep within the correct ProductLocation
object. I end up with chained AddSalesActivity
methods as in the following code.
Over the years I have seen this kind of a structure in many of the applications I worked. Sometimes even with longer chains. I was thinking about it today and this smells like a subtle repetition. Any ideas on a different way of handling this? Is there a way to come up with a better design?
class Solver{
List<ProductLocation> productLocations;
public void I开发者_Go百科mportSalesActivities{
//foreach sales activity read find the correct productLocation
//Call productLocation.AddSalesActivity)
}
}
class ProductLocation{
Forecaster forecaster;
public void AddSalesActivity(SalesActivity activity){
forecaster.AddSalesActivity(activity);
}
}
class Forecaster{
SalesActivityResolver resolver;
public void AddSalesActivity(SalesActivity activity){
resolver.AddSalesActivity(activity);
}
}
class SalesActivityResolver{
List<SalesActivity> resolvedActivities;
public AddSalesActivity(activity){
//update resolved activities based on complicated criteria.
}
}
In the way you describe it here, one could just cut out the classes ProductLocation
and Forecaster
, but I'm guessing they do other things not shown here and can therefore not be removed. I cannot help you anymore without a better understanding of the semantics of those objects and classes. My general advice would be that you should try to create an UML-Object-Diagram of your application for a simple scenario (not too many objects). This can help you to discover patterns and better understand the roles of your objects.
精彩评论