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

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

    Most of the answers don't explain what is cohesion, It is well defined in uncle bobs book clean code.

    Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of those variables. In general the more variables a method manipulates the more cohesive that method is to its class. A class in which each variable is used by each method is maximally cohesive. In general it is neither advisable nor possible to create such maximally cohesive classes; on the other hand, we would like cohesion to be high. When cohesion is high, it means that the methods and variables of the class are co-dependent and hang together as a logical whole.

    Let me explain it with a class definition

    class FooBar {
    private _bla;
    private _foo;
    private _bar;
    
    function doStuff()
    
       if(this._bla>10){
         this._foo = 10;
         this._bar = 20;
       }
    
    }
    function doOtherStuff(){
    
        if(this._foo==10){
           this._bar = 100;
           this._bla = 200;
        }
    }
    
    }
    

    If you see the above example the class is cohesive that means the variables are shared among the class to work together more variables are shared that means the class is highly cohesive and work as a single unit.

提交回复
热议问题