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!!
Making my comments into an answer..
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.