Tightly VS Loosely Coupled

Tight coupling:

When a class is dependent on other class. Suppose there are multiple classes in your Business layer just pick a class e.g. invoice and paste it in new project and build then may be class will not build as it will miss some another classes like invoice type, invoice detail or others. This means your invoice class is fully depend on other classes i.e. tightly coupled

Example of tight coupling:

 

 Collapse | Copy Code
public class Employee
    {
        public string firstName;
        public  Employee()
        {

        }
        public string GetEmployee(int employeeId)
        {
            string addressEmployee = string.Empty;
            Address objAdress = new Address();
            return  addressEmployee = objAdress.GetAddress(employeeId);
        }
    }

    public class Address
    {
       public  Address()
        {

        }
        public string GetAddress(int EmployeeId)
        {
            return "";
        }
    }

In this code there is nothing wrong. But if you want to get address of employee by type or by some other way then you will have to change Employee class. So here Employee class is tightly couple with address class.

Loose coupling:

in this scenario class is not dependent on other class and follow 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 use for decoupling. 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.

 

To avoid the dependency of address class we will use Dependency Injection. This provides the loose coupling between the object. With dependency injection you do not hard code your references to dependent objects
Example of loose coupling:

 

 Collapse | Copy Code
public class Employee
    {
        public string firstName;
        private IAddress objAddress;
        public  Employee(IAddress objAddress)
        {
            this.objAddress=objAddress;
        }
        public string GetEmployee(int employeeId)
        {
            string addressEmployee = string.Empty;
            return addressEmployee = objAddress.GetAddress(employeeId);
        }
    }

    public class Address
    {
       public  Address()
        {

        }
        public string GetAddress(int EmployeeId)
        {
            return "";
        }
    }

    public interface IAddress
    {
        string GetAddress(int EmployeeId);
    }
Advertisements