Now and again I end up with code along these lines, where I create some objects then loop through them to initialise some properties using another class…
ThingRepository thingRepos = new ThingRepository();
GizmoProcessor gizmoProcessor = new GizmoProcessor();
WidgetProcessor widgetProcessor = new WidgetProcessor();
public List<Thing> GetThings(DateTime date)
{
List<Thing> allThings = thingRepos.FetchThings();
// Loops through setting thing.Gizmo to a new Gizmo
gizmoProcessor.AddGizmosToThings(allThings);
// Loops through setting thing.Widget to a new Widget
widgetProcessor.AddWidgetsToThings(allThings);
return allThings;
}
…which just, well, feels wrong.
- Is this a bad idea?
- Is there a name of an anti-pattern that I’m using here?
- What are the alternatives?
Edit: assume that both GizmoProcessor and WidgetProcessor have to go off and do some calculation, and get some extra data from other tables. They’re not just data stored in a repository. They’re creating new Gizmos and Widgets based on each Thing and assigning them to Thing‘s properties.
The reason this feels odd to me is that Thing isn’t an autonomous object; it can’t create itself and child objects. It’s requiring higher-up code to create a fully finished object. I’m not sure if that’s a bad thing or not!
If you have complex intialization then you could use a Strategy pattern. Here is a quick overview adapted from this strategy pattern overview
Create a strategy interface to abstract the intialization
The initialization implementation that can be used by the strategy
And finally a service class that accepts the strategy implementation in an abstract way
You can then use the initialization strategies like so