I have been having issues grasping Dependency Injection(or let me say its benefit). So I decided to write two simple pieces of code of one without DI and the other with it.
So I have a class A
public class A {
public void foo(){
B b = new B();
b.fooB();
}
}
as can be seen above A
depends on B
, B
which is
public class B {
public void fooB(){
Log.e("s", "y");
}
}
and we can use A
like
public void do(){
A a = new A();
a.foo();
}
But it's said that A
should not simply initialize B
because it depends on it, however we should have have a service that have some sort of contracts between the two classes. For Example, please if I am wrong kindly let me know
So lets have an interface BService
public interface BService {
void fooB();
}
And B
becomes DiB
public class DiB implements BService {
@Override
public void fooB(){
Log.e("s", "y");
}
}
And A
becomes DiA
public class DiA {
BService bService;
public DiA(BService bService){
this.bService = bService;
}
public void foo(){
bService.fooB();
}
}
and we can use A
like
public void dIdo(){
BService service = new diB();
diA a = new diA(service);
a.foo();
}
So I read benefits of DI are :
- Testable codes : Because I can actually test both codes in JUnit(I dont want to post the test here to avoid long question)
- Decoupling: Its said that if class
B
changes thenA
shouldn't be affected, and I cant grasp that because If i changefooB()
in classB
tofooB2()
, i will have to change the override method inBService
which in turn means i will have to change it in classA
Both codes seems to work fine and I cant fathom benefit of one over the other, only that the other is more complex. So please can you enlighten me more on the benefits in the context of this simple A
and B
classes. What am I not getting?