views:

52

answers:

2

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?

+1  A: 

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).

Justin Niessner
So is allowing classes to be coupled to the exceptions they throw an acceptable compromise when unit testing?
DRock
+1  A: 

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.

Derek Greer