Example of tight coupling:
public class Employee { public Employee() { } public string GetEmployee(int employeeId) { Address objAdress = new Address(); return objAdress.GetAddress(employeeId); } } public class Address { public Address() { } public string GetAddress(int EmployeeId) { return ""; } } |
In above code there is nothing wrong. But Employee class is directly depending on address class object. So here Employee class is tightly couple with address class.
Loose coupling: A class is not dependent on other class and follows the single responsibility and separation of concern concept. A loosely-coupled class can be consumed and tested independently of other (concrete) classes.
Interfaces are a powerful tool to avoid the tight coupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface
Example of loose coupling:
public class Employee { private IAddress objAddress; public Employee(IAddress objAddress) { this.objAddress=objAddress; } public string GetEmployee(int employeeId) { return objAddress.GetAddress(employeeId); } } public class Address:IAddress { public Address() { } public string GetAddress(int EmployeeId) { return ""; } } public interface IAddress { string GetAddress(int EmployeeId); } |
In this code Employee class is not directly depend on address class object.
Tight coupling is not good concept, it is good only for small application which don't need to scalable. By loose coupling application can easily scalable and tested individually classes
No comments:
Post a Comment