What is tight and loose coupling? - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

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:

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