Loose coupling vs tight coupling of services

蓝咒 提交于 2019-12-12 00:56:49

问题


I understand that we at almost all times want to aim for loose coupling between components within an application & why.

But in the below example if someone could clarify as to why it isn't tightly coupled when we pass in a service as a parameter to a constructor so I could understand the logic that's going on under the hood.

export class Test(){

dataResults;

constructor(service: testService){

this.dataResults = service.getData()

}

}

回答1:


Tight coupling means : Code written is dependent on one class only, for example if i write

service:TestService;
constructor(){
this.service = new TestService();
this.dataResults = service.getData()
}

above code is tightly coupled because if tomorrow if i want to replace TestService with ActualService, I have to open files which is consuming TestService and have to do modification.

Now, Loose Coupling is reverse of tight coupling , means class is not dependent directly on the class whose service it consuming. In higher order language like C# , for loose coupling code is written like this

public class A{
  A(IB service) {//here IB is interface , on which A class is depedant
   //use service here 
  }
}

public class B : IB { }
public class C : IB { }

so now A id dedpend on IB , you can easily do this

A a = new A(new B());
or 
A a = new A(new C());

so its create that A is depend on IB which can be B or C. so it becomes loosely coupled with B and C.


Now coming to your code which Angular code,

In angular when we make use of any service in out component , we do register it via provider either at module or at component.

[{ provide: Logger , useClass: Logger}]

and then in component it used like

constructor(service: Logger){
  this.dataResults = service.getData()
}

Now tomorrow if i want to replace Logger with BetterLooger I just need to do like this

[{ provide: Logger , useClass: BetterLogger}]
or 
[{ provide: Logger , useClass: TestLogger}]

with out going in component code , thats how it becomes loose coupled. Or even its very helpful in testing of components also, where one want to replace actul service with MockService (check here : https://angular.io/guide/testing)

for above to work BetterLogger and TestLogger must extend Logger. you can go there and check in detail : https://angular.io/guide/dependency-injection

Further read : Dependency Injection and SOLID



来源:https://stackoverflow.com/questions/50772612/loose-coupling-vs-tight-coupling-of-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!