Tight and loose coupling

796 views Asked by At

Can someone please explain why the first block of code is tightly coupled while the other one is loosely coupled?

// tightly coupled
class Employee {  
    Address address;  
    Employee(){  
        address=new Address();  
    }  
}

//loosely coupled
class Employee { 
    Address address;  
    Employee(Address address){  
       this.address=address;  
    }  
} 
1

There are 1 answers

0
ares On BEST ANSWER

Employee class needs an Address, so Address is a dependency of Employee.

// tightly coupled
class Employee {  
    Address address;  
    Employee(){  
        address=new Address();  
    }  
}

In first case, Employee is responsible for creating the instance of Address and hence Employee is tightly coupled to Address.

//loosely coupled
class Employee { 
    Address address;  
    Employee(Address address){  
       this.address=address;  
    }  
} 

In second case Address will be given to Employee externally, so Employee is not tightly coupled to Address.

Let's take an example. Here we have two implementations of Address i.e. HomeAddress and WorkAddress. Since in first case Employee is responsible for instantiating Address, it's tightly coupled to either home or work address. However, in second case Employee class can use any Address that has been given to it.