内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
当前回答
我认为区别可以归结为以下几点:
内聚表示代码库的一部分在逻辑上形成单一原子单元的程度。 耦合表示单个单元独立于其他单元的程度。 在不破坏内聚的情况下存档完全解耦是不可能的,反之亦然。
在这篇博文中,我将对此进行更详细的描述。
其他回答
在面向对象编程语言中,模块内部的高内聚和模块之间的低耦合通常被认为与高质量有关。
例如,每个Java类中的代码必须具有较高的内部内聚性,但要尽可能地与其他Java类中的代码松散耦合。
Meyer的面向对象软件构建(第二版)的第3章对这些问题进行了很好的描述。
cohesion refers all about how a single class is designed. Cohesion is the Object Oriented principle most closely associated with making sure that a class is designed with a single, well-focused purpose. The more focused a class is, the cohesiveness of that class is more. The advantages of high cohesion is that such classes are much easier to maintain (and less frequently changed) than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes.
在上图中,我们可以看到,在低内聚情况下,只有一个类负责执行大量不相同的作业,这降低了可重用性和维护的机会。但是在高内聚的情况下,所有的作业都有一个单独的类来执行特定的作业,这样可以获得更好的可用性和可维护性。
关于内聚的最好解释来自Bob叔叔的《Clean Code》:
类应该有少量的实例变量。类的每个方法都应该操作一个或多个这样的变量。一般来说,方法操作的变量越多,该方法与其类的内聚性就越强。每个方法使用每个变量的类具有最大的内聚性。
一般来说,创建这种最大限度内聚的类既不可取,也不可能;另一方面,我们希望内聚力高。当内聚性高时,这意味着类的方法和变量是相互依赖的,并作为一个逻辑整体挂在一起。
保持函数小和参数列表短的策略有时会导致由方法子集使用的实例变量激增。当这种情况发生时,几乎总是意味着至少有一个其他类试图从较大的类中退出。您应该尝试将变量和方法分离到两个或多个类中,以便新类更具内聚性。
凝聚力:Co的意思是在一起,hesion的意思是粘在一起。粘结:不同物质的微粒粘在一起的系统
举个现实的例子: img礼貌
整体大于部分之和-亚里士多德。
Cohesion is an ordinal type of measurement and is usually described as “high cohesion” or “low cohesion”. Modules with high cohesion tend to be preferable, because high cohesion is associated with several desirable traits of software including robustness, reliability, reusability, and understandability. In contrast, low cohesion is associated with undesirable traits such as being difficult to maintain, test, reuse, or even understand. wiki Coupling is usually contrasted with cohesion. Low coupling often correlates with high cohesion, and vice versa. Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability. wiki
在软件工程中,内聚是指某个模块的元素属于一起的程度。因此,它是软件模块的源代码所表达的每个功能之间相关性的一种度量。
简单地说,耦合就是一个组件(再一次,想象一个类,尽管不一定)对另一个组件的内部工作方式或内部元素的了解程度,即它对另一个组件的了解程度。
我写了一篇关于这个的博客文章,如果你想用例子和图表来阅读更多的细节。我想它回答了你的大部分问题。