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
Address
i.e.HomeAddress
andWorkAddress
. Since in first caseEmployee
is responsible for instantiatingAddress
, it's tightly coupled to either home or work address. However, in second caseEmployee
class can use anyAddress
that has been given to it.