design-patternslanguage-agnosticdependency-injectionterminology

What is dependency injection?


There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn't it be used?


Solution

  • Dependency Injection is passing dependency to other objects or framework( dependency injector).

    Dependency injection makes testing easier. The injection can be done through constructor.

    SomeClass() has its constructor as following:

    public SomeClass() {
        myObject = Factory.getObject();
    }
    

    Problem: If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.

    Alternative solution:

    public SomeClass (MyClass myObject) {
        this.myObject = myObject;
    }
    

    myObject can be passed directly which makes testing easier.

    It is harder to isolate components in unit testing without dependency injection.

    In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.