Sunday, August 19, 2018

Inversion of Control (IOC)

http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/



IOC:

IoC is a design principle which recommends the inversion of different kinds of controls in object-oriented design to achieve loose coupling between application classes.
In this case, control refers to any additional responsibilities a class has, other than its main responsibility, such as control over the flow of an application, or control over the dependent object creation and binding (Remember SRP - Single Responsibility Principle).
If you want to do TDD (Test Driven Development), then you must use the IoC principle, without which TDD is not possible.

"Don’t call us we will call you".

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted. So for example rather than the caller calling the method.





Real life Example:

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

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

Example:

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.


          IOC:

  1. Service locator
  2. Events
  3. Delegates
  4. DI


  Types of DI:

  1. constructor DI
  2. Property DI
  3. Method DI




  Dependency Inversion Principle:

  The DIP principle also helps in achieving loose coupling between classes.
  It is highly recommended to use DIP and IoC together in order to achieve loose coupling.

          DIP suggests that high-level modules should not depend on low level modules. Both should depend on abstraction.












No comments:

Post a Comment