0

I am aware of the distinction between tight coupling and loose coupling, according to this articles: https://www.upgrad.com/blog/loose-coupling-vs-tight-coupling-in-java/

What I do not understand is the examples it uses.

For loose coupling, the Java code:

 class Volume {

   public static void main(String args[]) {

        Cylinder b = new Cylinder(25, 25, 25);

           System.out.println(b.getVolume());

   }

}

final class Cylinder {

    private int volume;

    Cylinder(int length, int width, int height) {

             this.volume = length * width * height;

    }

    public int getVolume() {

             return volume;

    }

}

For tight coupling, the Java code:

class Volume {

   public static void main(String args[]) {

        Cylinder b = new Cylinder(15, 15, 15);

           System.out.println(b.volume);

   }}

 class Cylinder {

   public int volume;

   Cylinder(int length, int width, int height) {

           this.volume = length * width * height;  }}

Can anyone please explain how does the second code make the two classes (Volume and Cylinder) bound together (tightly coupled)? Or what makes the first code loosely coupled? Thanks.

RyanKao
  • 321
  • 1
  • 5
  • 14

2 Answers2

2

Generally, in OOP you want to declare your class properties as private so you can encapsulate them. Doing this, you don't directly have access to them and you cannot change them by mistake. This is intended for code maintenance reasons, and it is especially useful when you have multiple developers that have access to the codebase, as you create a barrier between important class properties and the next developer.

This thing creates 2 problems though:

  • You cannot access the property value anymore - The getVolume() method comes into play here. This method is called a getter and is solely created to get the value of its related property by returning the property - not directly by accessing it.
  • You cannot change the property value anymore. - A setVolume(value) method (which is not present in your code) comes into play here. This method is called a setter and is solely created to change the value of its related property through a parameter - again, not directly.
Valentin Popescu
  • 174
  • 2
  • 12
-1

I think this is simple reason In Tight coupling code you may get the weakness: You are too dependent on the volume variable. For example if there a change reference field from volume to another, you must also change it in the calling function