Menus

Dec 24, 2018

What is dependency injection?


IoC is all about inverting the control. To explain in layman's term, suppose you drive a car to your work place, it means you control the car. IoC principle suggests to invert the control, meaning instead of driving the car yourself, you hire a cab where another person will drive the car. Thus it is called inversion of the control from you to the cab driver. You don't have to drive a car yourself and let the driver do the driving so that you can focus on your main work.

IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.








For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:


public class TextEditor {

private SpellChecker checker;

public TextEditor() {
this.checker = new SpellChecker();
}
}



What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public interface InterfaceSpellChecker{
}

public class SpellChecker extends InterfaceSpellChecker{
}

public class TextEditor {

private InterfaceSpellChecker checker;

public TextEditor(InterfaceSpellChecker checker) {
      this.checker = checker;
    }
}


In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.

In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:

InterfaceSpellChecker sc = new SpellChecker; // dependency
TextEditor textEditor = new TextEditor(sc);
Now the client creating the TextEditor class has the control over which SpellChecker implementation to use because we're injecting the dependency to the TextEditor signature.



Java Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection in java to move the dependency resolution from compile-time to runtime.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *