Posted by Himanshu Kumar | Last Updated: 21-Dec-17
Tight Coupling and
LooseCoupling between Objects:-
In java, a class can get its dependencies by using one of the following 4 ways.
(1) A class can directly create its dependency object with the new keyword.
(2) A class can get its dependencies by calling a factory method.
(3) A class can collect its dependency object from external memory like a registry.
(4) Some external person (entity) can inject class to object into class1.
When one object depends on another and if modifications done on dependency object is demanding the modifications in a caller object also then it is said to be tight-coupling
For example, consider the following 2 classes
In the above example, if a method in Car class is changed from
move() to go() then, in Travel class also we need to change in start journey() method. It means if dependencies object i.e. Car is changed then caller i.e. Travel also need changes.
It is a tight-coupling between objects.
In the above example, suppose if Travel class want another class, says Bike then we need to modify the travel class by replacing Car with Bike. This is also tight-coupling.
In order to avoid tight-coupling between objects, we should follow the below principles.
(1) Use POJI-POJO model for creating dependencies.
(2) Apply dependency-injection mechanism.
For example, create an interface Vehicle and define implementation classes like
Car, Bike, and Flight.
The importance of this model is, methods names in multiple classes will be same and a class cannot change method name. In Travel Class, take a reference of type Vehicle interface, so that it can store any implantation class object of that interface.
There is one vehicle object that is present in Travel object class and it will be needed by the container . So there is no need to make any changes in Travel class.
If the container injects the dependencies required for a class then it is called dependencies
For example, every servlet object needs two dependencies request and response. A servlet
container injects the dependencies to the servlet object. So it is also called dependency