Coupling and Cohesion in JAVA

Coupling 

Coupling is the degree to which one class knows about another class. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled…that's a good thing. If, on the other hand,class A relies on parts of class B that are not part of class B's interface, then the coupling between the classes is tighter…not a good thing. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.

Loose coupling is actaully minimizing the dependence of an object on other objects. In other words, you can change the implementation of a class without affecting the other classes.These properties make the code extensible and easy to maintain.




For example, consider two classes, A and B. If they do not use each other at all (neither of them instantiates the other, invokes a method on the other, and so on), they are not coupled. If A uses B (for example, instantiates B) but B does not use A, then they are loosely coupled. If both A and B use each other, then they are tightly coupled


Another criterion of loosely coupled classes is how they access each other’s members. Loose coupling demands that a class keep its members private and that the other class access them through getters and setters. Tight coupling is exhibited by accessing the public member of another class directly, as shown in in below code snippet.

TightlyCoupledClient.java

public class TightlyCoupledClient
{
    public static void main(String[] args) 
    { 
      TightlyCoupledServer server = new TightlyCoupledServer(); 
      server.x=5; //should use a setter method 
      System.out.println("Value of x: " + server.x);
      //should use a getter method 

    } 
}

 class TightlyCoupledServer 

    public int x = 0; //should be private


Cohesion  


Whereas coupling refers to how two classes interact with each other, cohesion refers to how a class is structured. A cohesive class is a class that performs a set of closely related tasks, or just one task (think of modular programming). If a class is performing a set of unrelated tasks (a noncohesive class), you should consider writing multiple classes (cohesive classes) or reshuffling the tasks (during design phase) until each class has a set of related tasks, or just one main task.


No comments:

Post a Comment