coding-stylesingle-responsibility-principledesign-principlescohesion

Why are maximally cohesive classes not advisable or possible to create?


I'm learning the book of Robert C. Martin "Clean Code" (2009) and I've stumbled upon the concept of cohesion (Chapter 10). Robert quotes:

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 ...

Unfortunately I didn't found a detailed explanation anywhere. Does anyone have an explanation for this with an real code examples?

Many thanks in advance!!


Solution

  • Making my comments into an answer..

    1. Maximal Cohesion, as defined in the book, in general implies that the methods provide overlapping functionality thus there is code duplication and they are not orthogonal. So this is bad design and should be avoided by refactoring common code and making the methods orthogonal as far as possible, thus eliminatiing maximal cohesion. So my point is that is why it is not advisable.
    2. However it is possible to create maximally cohesive classes and in some cases it is perfectly normal.

    One simple and practical example, I can think of, is classes representing geometrical shapes in computer-aided design.

    For example:

    class Circle{
       float[2] center;
       float radius;
    
       draw() {
         hardware.draw(center[0], center[1], radius);
       }
       print() {
         print('Cicrle at '+center[0]+','+center[1]+' with radius '+radius);
       }
       scale(s) {
         center[0] *= s;
         center[1] *= s;
         radius *= s;
       }
      intersectLine(line) {
        /* compute intersection based on line and circle coordinates using both cnter and radius variables */
      }
    }
    
    
    class Bezier{
       float[4] controls;
       draw() {
         /* .. */
       }
       print() {
         /* .. */
       }
       scale(s) {
         /* .. */
       }
       intersectLine(line) {
         /* .. */
       }
    }
    

    As one can see the shape classes are maximally cohesive and it is perfectly normal given the nature of the objects and their methods. Their variables are needed for any calculation of actual interest.

    Hope the examples and explanations are helpful.