Questioning one of the arguments 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/22 10:27 UTC
Read the original article Hit count: 221

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 there may be other arguments for dependency injection (which are out of scope for this question!), but easy creation of testable object graphs is not one of them, is it?

© Programmers or respective owner

Related posts about design-patterns

Related posts about object-oriented