Gradual approaches to dependency injection
- by JW01
I'm working on making my classes unit-testable, using dependency injection. But some of these classes have a lot of clients, and I'm not ready to refactor all of them to start passing in the dependencies yet. So I'm trying to do it gradually; keeping the default dependencies for now, but allowing them to be overridden for testing.
One approach I'm conisdering is just moving all the "new" calls into their own methods, e.g.:
public MyObject createMyObject(args) {
return new MyObject(args);
}
Then in my unit tests, I can just subclass this class, and override the create functions, so they create fake objects instead.
Is this a good approach? Are there any disadvantages?
More generally, is it okay to have hard-coded dependencies, as long as you can replace them for testing? I know the preferred approach is to explicitly require them in the constructor, and I'd like to get there eventually. But I'm wondering if this is a good first step.