Java Dependency Injection – Difference Between Efferent Coupling and Dependency Injection

dependency-injectionjava

I am working on research that analyzes dependency injection (DI) in Java projects. The more I read, the more I get confused by DI in relation to other frameworks and even software quality metrics.

I have been recently reading about afferent couplings (Ca), efferent couplings (Ce), and instability (I) with the formula below proposed by Martin Fowler:

I = (Ce/(Ce + Ca))

I noticed that the definition of efferent couplings is that it counts the number of classes the current class depends on. Is that essentially the same as dependency injection definition-wise, or are there more nuances to what is considered a dependency that has the DI framework as opposed to simply a class that the current class depends on?

Best Answer

They are different things.

(efferent) Coupling refers to classes your code won't compile without.

Dependency Injection is a way of passing in references to a class.

So

class Dog
{
   List<Leg> Legs {get;set;}
}

Dog is coupled to Leg

class Dog
{
   Dog(LegBuilder lb)
   {
       this.LegBuilder = lb
   }
   List<Leg> Legs {get;set;}
}

new Dog(legBuilder);//injecting the required legbuilder class

Dog Is coupled to Leg and LegBuilder, and we are injecting a LegBuilder

Related Topic