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

后端 未结 10 2237
伪装坚强ぢ
伪装坚强ぢ 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:34

    Cohesion is usually measured using one of the LCOM (Lack of cohesion) metrics, the original LCOM metric came from Chidamber and Kemerer. See for example: http://www.computing.dcu.ie/~renaat/ca421/LCOM.html

    A more concrete example: If a class has for example one private field and three methods; when all three methods use this field to perform an operation then the class is very cohesive.

    Pseudo code of a cohesive class:

    class FooBar {
      private SomeObject _bla = new SomeObject();
    
      public void FirstMethod() {
        _bla.FirstCall();
      }
    
      public void SecondMethod() {
        _bla.SecondCall();
      }
    
      public void ThirdMethod() {
        _bla.ThirdCall();
      }
    }
    

    If a class has for example three private fields and three methods; when all three methods use just one of the three fields then the class is poorly cohesive.

    Pseudo code of a poorly cohesive class:

    class FooBar {
      private SomeObject _bla = new SomeObject();
      private SomeObject _foo = new SomeObject();
      private SomeObject _bar = new SomeObject();
    
      public void FirstMethod() {
        _bla.Call();
      }
    
      public void SecondMethod() {
        _foo.Call();
      }
    
      public void ThirdMethod() {
        _bar.Call();
      }
    }
    

    The class doing one thing principle is the Single Responsibility Principle which comes from Robert C. Martin and is one of the SOLID principles. The principle prescribes that a class should have only one reason to change.

    Staying close to the Single Responsibility Principle could possibly result in more cohesive code, but in my opinion these are two different things.

提交回复
热议问题