内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
当前回答
内聚性是一个模块相对功能强度的指示。
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视图:类之间连接程度的定性度量 耦合水平 内容 常见 控制 邮票 数据 程序调用 类型使用 包含或导入 外部#
其他回答
在软件工程中,内聚是指某个模块的元素属于一起的程度。因此,它是软件模块的源代码所表达的每个功能之间相关性的一种度量。
简单地说,耦合就是一个组件(再一次,想象一个类,尽管不一定)对另一个组件的内部工作方式或内部元素的了解程度,即它对另一个组件的了解程度。
我写了一篇关于这个的博客文章,如果你想用例子和图表来阅读更多的细节。我想它回答了你的大部分问题。
内聚性是一个模块相对功能强度的指示。
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视图:类之间连接程度的定性度量 耦合水平 内容 常见 控制 邮票 数据 程序调用 类型使用 包含或导入 外部#
内聚这个术语在软件设计中确实有点违背直觉。
聚合力通常的意思是某物粘在一起很好,是统一的,其特征是像分子吸引力一样的强结合。然而,在软件设计中,这意味着力求类在理想情况下只做一件事,因此甚至不涉及多个子模块。
也许我们可以这样想。当一个部分是唯一的部分(只做一件事并且不能进一步分解)时,它具有最大的内聚性。这就是软件设计所需要的。内聚只是“单一责任”或“关注点分离”的另一种说法。
术语耦合是非常直观的,这意味着当一个模块不依赖于太多其他模块时,它所连接的那些模块可以很容易地被替换,例如遵循利斯科夫替换原理。
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.
在上图中,我们可以看到,在低内聚情况下,只有一个类负责执行大量不相同的作业,这降低了可重用性和维护的机会。但是在高内聚的情况下,所有的作业都有一个单独的类来执行特定的作业,这样可以获得更好的可用性和可维护性。
简单地说,内聚意味着一个类应该代表一个单一的概念。
如果类的所有特性都与类所代表的概念相关,那么类的公共接口就是内聚的。 例如,与其拥有CashRegister类,不如拥有CashRegister和Coin功能,将其整合为2个类- CashRegister和Coin类。
在耦合中,一个类依赖于另一个类,因为它使用类的对象。
高耦合的问题在于它会产生副作用。一个类中的一个更改可能导致另一个类中出现意外错误,并可能破坏整个代码。
通常,高内聚和低耦合被认为是高质量的OOP。