My team is muddling through implementing dependency injection in a PHP project using a homebaked DI container. Our first iteration of DI was perhaps taken to the extreme, and even exceptions are being injected into classes that depend on them.
Is this a good practice or overkill?
Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID's dependency inversion and single responsibility principles.
More specifically, dependency injection is effective in these situations: You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.
In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.
Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.
The purpose of Dependency Injection is to invert the responsibility of obtaining dependencies which are the collaborators used by an object to facilitate configuration or collaborative behavior.
In general, exceptions are inherent to the contract of a given class. That is to say, exceptions are part of the implicit or explicit contract for how a component behaves in the event of a fault and therefore don't lend themselves to being switched out with derivatives. Events also don't typically have behavior, so abstracting them for the purpose of test isolation isn't particularly valuable either. Furthermore, because events typically only represent a fault state or event, being able to inject derivatives of the exception also isn't particularly valuable since any consumers of the component would need to code against the base exception contract (i.e. any additional properties wouldn't be seen).
There are perhaps a few legitimate reasons you might want to inject an exception, such as with the design of an exception handling component which rethrows exceptions after logging, wrapping, etc., or perhaps where the construction of the exception itself requires external resources to achieve (though that need would itself give me pause), but in general I wouldn't say you should be decoupling how a component reports its fault states from the components themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With