Inquiry about cohesion in java programming

285 views Asked by At

How would you define the following code?

a) High cohesion

b) Low cohesion

I would say High as even though takeAndGlue() does 2 things they are called with 2 separate methods, hence the stackTrace is traceable.

public class Assembler()
{
    public void take()
    {
        System.out.println("Take the thing");
    }
    public void glue()
    {
        System.out.println("Glueing the thing");
    }
    public void takeAndGlue()
    {
        take();
        glue();
    }
}
3

There are 3 answers

0
KocsisLaci On

This class shows low cohesion because take() and glue() can be called separately but that makes no sense if not in the right order. In other words: take(), glue() should not be public.

0
Dhrumil Shah On

This is an example of low cohesion:

class Cal
{


     public static void main(String args[])
     {

          //calculating sum here
          result = a + b;
          //calculating difference here
          result = a - b;
          //same for multiplication and division
     }
}

this is an example of High cohesion:

class Cal
{

     public static void main(String args[])
     {

          Cal myObj = new Calculator();
          System.out.println(myObj.SumOfTwoNumbers(5,7));
      }


     public int SumOfTwoNumbers(int a, int b)
     {

          return (a+b);
     }

     //similarly for other operations

}

But high cohesion implies that the functions in the classes do what they are supposed to do(like they are named). And not some function doing the job of some other function. So, the following can be an example of high cohesion:

0
Amol Sonawane On

Wikipedia says..

As applied to object-oriented programming, if the methods that serve the given class tend to be similar in many aspects, then the class is said to have high cohesion.

In your example, all the three methods are doing work related to assembly, and this class can be said to have high cohesion.