Tight Coupling and loose coupling
Tight Coupling:
Tightly coupled object is an object that needs to know quite a bit about other objects and are usually highly dependent on each other’s interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects.
Example
class Plus { public int doTheMath(int a, int b) { return a + b; } } class Minus { public int doTheMath(int a, int b) { return a - b; } } public class Arithmetic { public static void main(String[] args) { Plus plus = new Plus(); System.out.println(plus.doTheMath(2, 3)); } }
In tight Copuling if we have to change the mode of operation from + to – (in this example) we have to change a lot of code, like this
Minus minus = new Minus(); System.out.println(minus.doTheMath(2, 3));
Loose Coupling
Loose coupling is a design goal that seeks to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.
Example
interface Calculate { int doTheMath(int a, int b); } class Plus implements Calculate { @Override public int doTheMath(int a, int b) { return a + b; } } class Minus implements Calculate { @Override public int doTheMath(int a, int b) { return a - b; } } public class Arithmetic { public static void main(String[] args) { Calculate calc = new Plus(); System.out.println(calc.doTheMath(2, 3)); } }
In the above example if we have to change the operation from plus to minus we need only one change :
Calculate calc = new Minus();
Just assume your code when you are dealing with 10-20 dependencies in your class. Loosely coupled classes will make changing cases very easy and it’s also more realistic