Skip to main content

Dependency Injection - You're doing it wrong!

So I have worked at a lot of places and seen a lot of different styles of programming.  Early on in my career, I became acquainted with the concept of dependency injection.  It was a hard topic to grasp, but I have learned understand it deeply.  Now, when I step into a new application that uses it, I can very quickly see the flaws in the implementation, and there's a common one I want to talk about today: global singletons.  But we'll get to that in a minute.

What is Dependency Injection?


Dependency Injection is exactly what it sounds like.  You use it to inject your dependencies.   The unique part about Dependency Injection though, is that you can do this at runtime.  Now this sounds fancier than it is.  By inject we don't mean they're downloaded for you.  You still have to have all of the parts installed where you want to run your app.

Dependency Injection is somewhat of a complicated topic to a newbie.  Let's start with defining the word dependency here.  Specifically, DI is about classes, but everyone who talks about DI talks about Interfaces.  This is because DI does something unique among software patterns.  It doesn't decrease the amount of code you have to write, it increases it.  That's right, when you start using Dependency Injection, you can expect to write a lot more code, a third as much as you are currently writing or more (beyond 100%) on top of your existing workload.  For every class you write, you need to write a matching interface that provides access to all of the class's public properties, and the class needs to implement that interface.

Then Why Use It?


Like all software patterns, DI is about making your code easier to work with.  The magic of DI is the interface.  Interfaces are simple stubs of classes that essentially mean "any class that implements this interface must have these public properties".  That's it.  It's a set of rules for creating a class.  This makes it easier to write your class later, because you know it only needs public properties X, Y, and Z.  Let's look at a real life example.  I'm pulling this example from a library written by a good friend of mine who's worked with me at some of my big name jobs.  Here's the full library for reference: https://github.com/danielkrainas/squire

First, let's look at an interface he created for storing data.


namespace Squire.Storage
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public interface IBlob : IBlobItem
    {
        void SetPermissions(BlobPermissions permissions);

        void Delete();

        void PerformRead(Action<Stream> readerActivity);

        void PerformWrite(Action<Stream> writerActivity);

        void CopyTo(IBlobContainer container, string copyName = "");
    }
}

Pretty simple right?  Basically his interface offers CRUD.  Create, Read, Update, Delete, and a few other minor features.  OK, it's not perfect CRUD, but I'm sure he intended for it to be that way.

If you've written code for storage, you can imagine how having this template makes it a little easier to write the class that implements IBlob, but the value of this interface is the ability to use it for Dependency Injection.  Let's take a look at another Interface (because they're short) that uses the IBlob interface as if it were an object.


namespace Squire.Storage
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public interface IBlobContainer : IBlobItem
    {
        IBlob GetBlob(string name);

        void CreateIfNotExists();

        void SetPermissions(BlobContainerPermissions permissions);

        IBlobContainer GetContainer(string containerName);

        void Delete();

        IEnumerable<IBlob> SearchBlobs(string filter, bool recursive = false);

        IEnumerable<IBlobContainer> SearchContainers(string filter, bool recursive = false);

        IEnumerable<IBlobItem> Search(string filter, bool recursive = false);

        IEnumerable<IBlobItem> Contents
        {
            get;
        }
    }
}

So we can create objects and refer to the types by the interface instead of by the class.  But ultimately, an interface is not a class.  You cannot create an instance of an interface.  You can only create an instance of a class.  What we get is a state where you can rely on any class that implements your interface to have those same public properties.  They call this a Contract.

Wait, this is about inheritance?


No.  This is where we talk about the second thing people talk about with Dependency Injection: Inversion of Control.  The benefit of having these interfaces is that you no longer have to worry about HOW something will be implemented.  You can pass off individual classes even between developers and they no longer have to know what each other are doing.  They have an interface that binds them.  That interface tells you in a very concise way what the architecture, the structure of your application is.  The individual class implementations can be good or bad, but you don't have to know how one class works in order to work with another.  Instead, you only need to know what public properties that class will provide you, and you can build your logic around it.

Inversion of Control is where you decide which class to inject at runtime.  You get control of your implementation at runtime, instead of at compile time.  Your control is "inverted" from the traditional implementation..  If you think about a traditional implementation of the above interfaces, BlobContainer would have an instance of Blob.  Which means that if you change Blob, you can easily break BlobContainer.  But if BlobContainer relies on an IBlob interface, then you can change Blob all day.  As long as it implements IBlob, BlobContainer will be unaffected by those changes.  BlobContainer now has control over the contract it chooses to support with objects that implement IBlob, rather than the other way around.

This is what Dependency Injection gives us.  It creates a clear application structure that we can rely on.  But it has a bonus feature.  Interfaces can be implemented by multiple classes.  Since we can swap out these classes at runtime, which means: we can swap out our implementation.  For this reason, if you're working in a statically typed language, you should always use this Interface pattern.  In fact, that pattern has been around a while.  It's called the Revealing Interface Pattern, and has varying names and slightly modified versions in many languages, even those that are not statically typed.

So what's wrong?


Because you can change your implementation at runtime, you can do some crazy things.  The craziest I have seen is that some people use their DI library to create "global singletons" that they can access throughout their application.  Globals are bad.  Singletons are bad because people treat them like globals.  Wrapping singletons in a Dependency Injection library adds extra weight.  To add that extra weight in order to do something that's bad in the first place is so dumb.

Use Interfaces to make your code easier to follow, and IoC in order to make it easier to change out dependencies (read: classes).  Don't use DI to make your dependencies global.  Dependency Injection: You're doing it wrong.

Comments

Popular posts from this blog

How to identify a skilled programmer during an interview

How does one identify a skilled programmer?  No company that has interviewed me could tell the difference between myself and other programmers they'd interview.  The interview process is truly a game of luck in this industry--on both sides.  Both the programmer and the company are basing their actions entirely on luck.

Companies have come up with numerous methods to attempt to discern a good programmer from a bad one.  The best tricks they have include a series of math problems, algorithms, problem solving technique tests, and even obscure programming questions, some without definitive answers.  As an example: Is there an authoritative source of information on the core principles that define object oriented programming?  I've heard everywhere from 3 to 7.  In a field of research about a synthetic concept, an authoritative answer is almost impossible to obtain.

Programmers were then forced to study to the interview.  Careercup is one of my favorite sites for this.  This almost …

When Is Software Done?

I have some very exciting news.  A piece of software I've been working on for over 2 years is released to the general public!  This is a little exciting if it were software I'd been working on for some big company.  It's very exciting because it's software I have been working on for my company.  That's right!  My company is ready to start selling software and start making money!

I'm not gonna use this blog post to talk about my company and what it does.  You can read about that in our press release.  Instead, I'm going to talk about the software industry and the concept of done.  Because, as with everything, it's more complicated than it seems.

Software is never really done
Actually that's a misnomer.  Software can really be done.  But done is sort of a quantum state--there and not there at the same time.  First and foremost, anyone can understand that software that works is complete.  If the software's purpose is to process a credit card, if th…

Managing Programmers

Working with other programmers is tricky.  That said, it's nothing compared to the job of managing programmers.  One of my favorite quotes about Perl is that (paraphrased) "a Perl developer is like a rockstar.  Now imaging having a bunch of rockstars in one room together and you will understand why you don't want an entire team of Perl developers."  It's not about Perl here though. What's important to understand is that any developer worth his salt is going to be like a rockstar.  And yes, there are a lot of professional developers out there who aren't worth their salt, but that's for another post another day.  Rockstar may not be the right term here, but think of it this way.  These guys are smart.  They may not be geniuses, but there's going to be things that they know that you don't and probably never will.

I've seen it more than once and it's not going to make some Product Managers happy, but I'm going to state a fact, an eleph…