Pages

Thursday, January 5, 2012

What is tight and loose coupling?

Tight coupling: A class is dependent on other class. Interconnected classes know the internal detail of each other. Suppose there are multiple classes in your Business layer just pick a class e.g. Employee and paste it in new project and build then may be class will not build as it will miss some another classes like Employeetype, Address or others. This means your Employee class is depend on other classes i.e. tightly coupled

Example of tight coupling:

publicclassEmployee

{

public Employee()

{

}

publicstring GetEmployee(int employeeId)

{

Address objAdress = newAddress();

return objAdress.GetAddress(employeeId);

}

}

publicclassAddress

{

public Address()

{

}

publicstring 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:

publicclassEmployee

{

privateIAddress objAddress;

public Employee(IAddress objAddress)

{

this.objAddress=objAddress;

}

publicstring GetEmployee(int employeeId)

{

return objAddress.GetAddress(employeeId);

}

}

publicclassAddress:IAddress

{

public Address()

{

}

publicstring GetAddress(int EmployeeId)

{

return"";

}

}

publicinterfaceIAddress

{

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

Did you like this article? Did it Help you Solve your Problem? You can get the all the latest articles published at wikyapps in your email inbox by entering your email address below. Your address will only be used for mailing you the articles, and each one will include a link so you can unsubscribe at any time.