1

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;  
    }  
} 
MWiesner
  • 8,868
  • 11
  • 36
  • 70
abhi
  • 117
  • 13
  • Possible duplicate of [Coupling and cohesion](http://stackoverflow.com/questions/39946/coupling-and-cohesion) – André Dion Dec 24 '16 at 16:05
  • thanks for your efforts andre , i already knew the definition , It would have been wonderful , if you had answered in terms of the above code which i have mentioned. – abhi Dec 24 '16 at 17:48
  • 1
    We would need to look for the exact case of use to determine if the case happens to be tightly coupled. In your case, with `Employee` and `Address` entities, it makes sense for the `Employee` class not to create the address itself, but to have it injected externally on the object creation or using a setter. This way we allow an external framework (like hibernate or spring) manage it and we can have many employees with the same address. – Aritz Dec 25 '16 at 10:56

1 Answers1

2

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.

ares
  • 4,283
  • 6
  • 32
  • 63