1

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
K. Elghali
  • 35
  • 1
  • 5
  • do you understand why it is not advisable to do so? It means that the code and methods are not modular and orthogonal to each other, with possibly lorts of duplication and overlaping of functionality that a refactoring is needed. Now, about the possibility part, I can make examples of very cohesive classes as a proof of concept but they would not be realistic cases – Nikos M. Jun 08 '20 at 12:08
  • Maybe a practical example of very cohesive classes are classes representing geometrical shapes in design. Almost all the variables for each shape are used in almost all the methods. Eg a circle has center and radius as variables and these are used in all the methods that are relevant to a circle object, eg `draw`, `scale`,`move`, `print`, `computeIntersectionWithLine`, etc.. – Nikos M. Jun 08 '20 at 12:13

1 Answers1

1

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.

Nikos M.
  • 8,033
  • 4
  • 36
  • 43