On Dependency Injection

I just read an article about eliminating dependencies whose basic thesis is that instead of having a class that depends on something that can give you a value, just depend on that value directly.

His example (which you can read more fully in the article) is that instead of having

    public InvoiceGenerator(IConfigurationReader configurationReader)
    {
        _configurationReader = configurationReader;
    }

and later on calling

        var watermarkText = _configurationReader.Get<string>("invoiceWatermarkText");
        if (!String.IsNullOrEmpty(watermarkText))

to get the text we need, just request the text directly:

    public Invoice GenerateInvoice(string watermarkText)
    {
        if (!String.IsNullOrEmpty(watermarkText))

There are two obvious problems with this, which you will hit extremely quickly in real code.

One of them, pointed out by a comment by LeszekP, is that most of the time you will require more than a single value from an interface. Worse, some of them will only be required in specific cases (behind if branches).

The second one is that this method of eliminating the dependencies has actually increased them: instead of having one dependencies from the current class to the IConfigurationReader interface, we now have ALL clients of the current class suddenly requiring that dependency, because all of them now need to pass on the watermark value.

In short, although I would very much appreciate a clean way of reducing dependencies between classes, I don't believe this is the right method.

Comments

Popular posts from this blog

Posting dynamic Master / Detail forms with Knockout

Comparing Excel files, take two

EF Code First: seeding with foreign keys