Hans' Blog

Dependency Injection vs Dependency Inversion

July 19, 2018

I got super confused about Dependency Inversion when I stumbled upon it.

I was watching a video about Dependency Inversion as part of SOLID principle. The video rolls out as if we are building a dependency injection code, where your high-level class will accept low-level dependent class as part of constructor. One comment on the video that states the explanation in the video is not accurate got me digging.

At this point in time, I am quite familiar with Dependency Injection from my experience with Spring Framework. The idea is to let dependencies of an object be supplied (by another object or a method), as opposed to building or finding the dependencies by the object (thanks, Wikipedia!).

Then I looked at Dependency Inversion principle, whereby it talks about modules should depend on abstractions and not details. Sounds very close to Dependency Injection implementation in Spring in which we can guide the injection by using interfaces, as opposed to the implementating classes.

The Dependency Injection Wikipedia page states that as part of inversion of control, Dependency Injection supports the Dependency Inversion principle!

Now it's much clearer: Dependency Inversion principle is about using in interfaces (as per Java term1) while the object itself can still build or find the dependency it needs as long as it fits the interface, whereas Dependency Injection is about the object just receiving its dependent object.

Pseudocodes below:

// Dependency Inversion principle

interface Animal { /* ... */ }
class Dog implement Animal { /* ... */ }

class Pet {
    Animal myPet;

    public Pet() {
        myPet = new Dog();
    }
}

class Main {
    public static void main(String[] args) {
        Pet pet = new Pet();
    }
}
// Dependency Injection

interface Animal { /* ... */ }
class Dog implement Animal { /* ... */ }

class Pet {
    Animal myPet;

    public Pet(Animal dependencyInjection) {
        myPet = dependencyInjection;
    }
}

class Main {
    public static void main(String[] args) {
        Animal animalToBeInjectedAsDependency = new Dog();
        Pet pet = new Pet(animalToBeInjectedAsDependency);
    }
}

1 Not every programming languages has the concept of interface, but basically the idea of interface is an abstraction layer that has certain behaviors without needing to know the underlying implementation.