Let’s say for example I am developing a fictional class called WidgetMaker
. If the class depends at some point on lookup data stored in a database is it better to design the class with a dependency on the data or a service to fetch the data?
Does it make more sense to do this?
public class WidgetMaker {
public WidgetMaker(LookupData lookupData) {
}
public Widget MakeWidget() {
if(lookupData.SomeField) {
return new Widget("blue");
}
else {
return new Widget("red");
}
}
}
-or this-
public class WidgetMaker {
private readonly LookupDataRepo lookupRepo
private LookupData lookupData;
public WidgetMaker(LookupDataRepo lookupRepo) {
lookupRepo = lookupRepo;
}
public Widget MakeWidget() {
if(lookupData == null) {
lookupData = lookupRepo.GetLookupData();
}
if(lookupData.SomeField) {
return new Widget("blue");
}
else {
return new Widget("red");
}
}
}
The first way seems like the “right” design because we’re injecting what the class needs. It makes the class easier to unit test. Otherwise we need to pass in a mock repo just to test the logic.
On the flip-side, it seems like we're pushing the fetching of data to somewhere else, maybe a WidgetMakerFactory
class. Then whatever class that needs a WidgetMaker
, would instead get dependency on WidgetMakerFactory
which seems like we’re repeating the same issue.
public class WidgetController : Controller {
private WidgetMakerFactory factory;
public WidgetController(WidgetMakerFactory factory) {
this.factory = factory;
}
public ActionResult Index() {
return View(factory.Create().MakeWidget())
}
}
lookupData
expected to be the same for all users, threads, etc. or could it change? Are input parameters required to get the rightlookupData
?lookupData
might change at some point in the database, so it could differ from one request to another