@rkenmi - Inversion of Control (IoC)

Inversion of Control (IoC)

Inversion of Control (IoC)

Back to Top

Updated on September 8, 2018

IoC, or Inversion of Control, is essentially a way of dealing with dependency injection. Frameworks like Spring are well known for this idea.

In traditional control flows, a subclass may depend on another class for certain dependencies. There are a few problems with this approach.

  • Objects can be strongly dependent on each other. What if some objects have to be swapped or changed?
  • May have to re-write the same construction code over and over.
  • Sometimes it is difficult to determine where the dependencies should be constructed and passed.
  • Can be hard to manage

Utilizing dependency injection, a technique in which objects supply other objects with dependencies, we can have a container that has a specific purpose of supplying dependencies and nothing else. This is the IoC way, and it has some benefits that are worth serious consideration.

  • Objects can be loosely coupled, with no knowledge of where the dependencies come from or how it is created. This means less code.
  • Classes no longer have the responsibility of constructing dependencies. The dependencies are brought to the classes already constructed. In addition, we can focus our shift to using the API given by the dependencies.
  • Eliminates redundant code and copied code. Promotes DRY (Don't Repeat Yourself) behavior.
  • Dependency management is reduced to a single point of failure; if the IoC container fails, then we know where to debug.
  • Objects are injected at run-time, rather than compile-time. This reduces the amount of code in the class files significantly.

Article Tags:
JavaSpringInversion of ControlDependency Injection