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;
}
}
Employee class needs an Address, so Address is a dependency of Employee.
In first case, Employee is responsible for creating the instance of Address and hence Employee is tightly coupled to 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
Addressi.e.HomeAddressandWorkAddress. Since in first caseEmployeeis responsible for instantiatingAddress, it's tightly coupled to either home or work address. However, in second caseEmployeeclass can use anyAddressthat has been given to it.