[我正在学习罗伯特·C·马丁(Robert C. Martin)的《清洁代码》(Clean Code)(2009年)一书,但偶然发现了凝聚力的概念(第10章)。罗伯特语录:
最大程度地使用每种方法的每个变量的类 凝聚力。通常,既不建议也不可行 这样的最大内聚类 ...
很遗憾,我没有在任何地方找到详细说明。有人用真实的代码示例对此进行解释吗?
非常感谢!
使我的评论成为答案。
我可以想到的一个简单而实际的示例是表示计算机辅助设计中的几何形状的类。
例如:
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) {
/* .. */
}
}
正如人们所看到的,形状类具有最大的内聚性,考虑到对象的性质及其方法,这是完全正常的。计算实际兴趣时需要使用它们的变量。]>
希望示例和说明会有所帮助。