Where loose and tight coupling would be used as a real scenario?

advertisements

I have referred this link, Difference between loose and tight coupling in Java?

After I referred this still I am in confusion and do not understand at all.

As a Java Beginner, I could not be able to understand it easily. Please can anyone suggest a better example?

Can anyone say me, whats the importance of coupling in java and why, where, how and when does it would be needed while designing a code?


Tight Coupling

  • In complex cases the logic of one class will call the logic of another class just to provide the same service

  • If this happen there is the so called tight-coupling between the two classes.

  • In this case the first class that wants to call the logic from the second class will have to create an object from the second class

Example: we have two classes first is traveller and the second is a car. Traveller class is calling logic of car class; in this case traveller class creates an object of car class.

This will mean the car class will depend on the traveller object.

Public class Traveller {
    Car c = new Car();
    Public void startJourney() {
        c.move();
    }
}

Public class Car {
    Public void move(){
        ...
    }
}

Here traveller object is tightly coupled with car object.
If traveller wants to change from car to plane then the whole traveller class has to be changed like the following:

Public class Traveller {
    Plane p = new Plane();
    Public void startJourney() {
        p.move();
    }
}

Public class Plane {
    Public void move(){
        ...
    }
}

Loose Coupling

  • Our main object, traveller in this case will allow an external entity, a so called container to provide the object. So traveller doesn't have to create an own class from the car or plane object it will get it from the container

  • When a object allow dependency injection mechanism.

  • The external entity, the container can inject the car or plane object based on a certain logic, a requirement of the traveller.

Example:

Public class Traveller {
    Vehicle v;

    Public void setV(Vehicle v) {
        this.V = V;
    }
    Public void startJourney() {
        V.move();
    }
}

Here traveller class injects either a car or a plane object. No changes required in traveller class if we would like to change the dependency from car to a plane.

Traveller class took a vehicle reference, so an external object (Container) can inject either car object or plane object, depends on requirement of traveller.