IOC(Inversion Of Control)

What is IOC(Inversion Of Control):

Allowing your clients to define and use dependency of your service instead you defining it.

Example
You are creating a service called TextEditor and you want to use an open source library for spell check. 

Client ----> Service ----> Dependency

There are two ways you can do this.
  1. Define dependency in you service and let client do not worry about that.
  2. Create Instance on Dependency and let client decide which dependency to use.
Let's understand each way through code snippet along with pros and cons. 

1. Define dependency in you service and let client do not worry about that:

Service: Service will look like
public class TextEditor {

    private SpellChecker checker;

    public TextEditor() {
        this.checker = new SpellChecker();
    }
}
Client: Client will use service like
TextEditor textEditor = new TextEditor();

Pros:

  1. Your client does not need to worry or know about spell checker.

Cons

  1. Every time SpellChecker changes service needs to changed and when service changes client needs to update as per new changes. For Example if SpellChecker makes default constructor private and only allow parameterized constructor. Service and client both will have to make change.

Create Instance on Dependency and let client decide which dependency to use:

Service: Service will look like
public class TextEditor {

    private IocSpellChecker checker;

    public TextEditor(IocSpellChecker checker) {
        this.checker = checker;
    }
}
Client: Client will use service like
SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);

Pros:

  1. As a service provider you do not need to worry about any changes in dependency. If SpellChecker makes its default constructor private and allows only parameterized constructor. Only clients will have make changes at their end.
  2. Client can use dependency as per the requirement. If there is new SpellChecker in market with better feature client can use it without asking TextEditor to make any changes

Cons:

  1. Little extra overhead to your client.

Was this article helpful? Please provide you feedback in comments section below. Please add comments if you find anything wrong or want to add something that will make this article more better.

Thank you for reading :-)

Comments

Popular posts from this blog

JAVA | Exception Handling | Introduction

Design Pattern