内聚和耦合之间的区别是什么?

耦合和内聚如何导致软件设计的好坏?

举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?


当前回答

我认为区别可以归结为以下几点:

内聚表示代码库的一部分在逻辑上形成单一原子单元的程度。 耦合表示单个单元独立于其他单元的程度。 在不破坏内聚的情况下存档完全解耦是不可能的,反之亦然。

在这篇博文中,我将对此进行更详细的描述。

其他回答

内聚性是一个模块相对功能强度的指示。

A cohesive module performs a single task, requiring little interaction with other components in other parts of a program. Stated simply, a cohesive module should (ideally) do just one thing. Conventional view: the “single-mindedness” of a module OO view: cohesion implies that a component or class encapsulates only attributes and operations that are closely related to one another and to the class or component itself Levels of cohesion Functional Layer Communicational Sequential Procedural Temporal utility

耦合表示模块之间的相对相互依赖。

耦合取决于模块之间的接口复杂性 指向一个模块的条目或引用,以及什么数据 通过接口传递。 传统观点: 一个组件与其他组件和外部世界的连接程度 OO视图:类之间连接程度的定性度量 耦合水平 内容 常见 控制 邮票 数据 程序调用 类型使用 包含或导入 外部#

关于内聚的最好解释来自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

简单地说,内聚意味着一个类应该代表一个单一的概念。

如果类的所有特性都与类所代表的概念相关,那么类的公共接口就是内聚的。 例如,与其拥有CashRegister类,不如拥有CashRegister和Coin功能,将其整合为2个类- CashRegister和Coin类。

在耦合中,一个类依赖于另一个类,因为它使用类的对象。

高耦合的问题在于它会产生副作用。一个类中的一个更改可能导致另一个类中出现意外错误,并可能破坏整个代码。

通常,高内聚和低耦合被认为是高质量的OOP。