Questioning the motivation for dependency injection: Why is creating an object graph hard?
Posted
by
oberlies
on Programmers
See other posts from Programmers
or by oberlies
Published on 2014-08-21T16:58:45Z
Indexed on
2014/08/21
22:26 UTC
Read the original article
Hit count: 343
Dependency injection frameworks like Google Guice give the following motivation for their usage (source):
To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph.
Building object graphs by hand is labour intensive (...) and makes testing difficult.
But I don't buy this argument: Even without dependency injection, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way:
class BillingService {
private final CreditCardProcessor processor;
private final TransactionLog transactionLog;
// constructor for tests, taking all collaborators as parameters
BillingService(CreditCardProcessor processor,
TransactionLog transactionLog) {
this.processor = processor;
this.transactionLog = transactionLog;
}
// constructor for production, calling the (productive) constructors of the collaborators
public BillingService() {
this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog());
}
public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {
...
}
}
So dependency injection may really be an advantage in advanced use cases, but I don't need it for easy construction and testability, do I?
© Programmers or respective owner