What is high cohesion and how to use it / make it?

后端 未结 10 2239
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 05:17

I\'m learning computer programming and at several places I\'ve stumbled upon the concept of cohesion and I understand that it is desirable for a software to have \"high cohe

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 05:39

    This is an example of low cohesion:

    class Calculator
    {
    
    
         public static void main(String args[])
         {
    
              //calculating sum here
              result = a + b;
              //calculating difference here
              result = a - b;
              //same for multiplication and division
         }
    }
    

    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:

    class Calculator
    {
    
    
         public static void main(String args[])
         {
    
              Calculator myObj = new Calculator();
              System.out.println(myObj.SumOfTwoNumbers(5,7));
          }
    
    
         public int SumOfTwoNumbers(int a, int b)
         {
    
              return (a+b);
         }
    
         //similarly for other operations
    
    }
    

提交回复
热议问题