Many people come from frameworks that implement Dependency Injection and IoC containers for everything (in my case Angular 2+), so, this group of people will try to use dependency injection and IoC containers in everything even outside those frameworks.
But, most of the implementation using DI is not using it to implement the Dependency inversion principle from SOLID (which is kind of impossible to implement without DI), they are just using it as a way of making the class easily testable doing something like this:
class Dependency {}
class SomeClass {
constructor(private dependency: Dependency) {}
}
But why not this:
class Dependency {
static global = new Dependency();
}
class SomeClass {
protected dependency = Dependency.global;
}
We can easily mock/stub this dependecy only by extending it:
class TestSomeClass extends SomeClass {
protected dependency = mock<Dependency>();
}
Is there any problem we could face by doing this instead of dependency injection?
SomeClass objectUnderTest = new SomeClass(mock<Dependency>())
?