When implementing dependency injection, should exceptions be injected?
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 t开发者_如何转开发o the extreme, and even exceptions are being injected into classes that depend on them.
Is this a good practice or overkill?
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.
That sounds like a good bit of overkill.
When an Exception is thrown, it should be providing some kind of useful information through its message and type.
If you're injecting the Exception class to use, that means the type of the Exception is no longer useful in finding out what the problem really is (because you already know the type since you injected it).
精彩评论