内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
内聚和耦合之间的区别是什么?
耦合和内聚如何导致软件设计的好坏?
举些什么例子来概括这两者之间的区别,以及它们对整体代码质量的影响?
当前回答
内聚指的是类(或模块)可以做什么。低内聚意味着这个类会做各种各样的动作——它很宽泛,不关注它应该做什么。高内聚意味着类专注于它应该做的事情,即只有与类的意图相关的方法。
低内聚的例子:
-------------------
| Staff |
-------------------
| checkEmail() |
| sendEmail() |
| emailValidate() |
| PrintLetter() |
-------------------
高内聚的例子:
----------------------------
| Staff |
----------------------------
| -salary |
| -emailAddr |
----------------------------
| setSalary(newSalary) |
| getSalary() |
| setEmailAddr(newEmail) |
| getEmailAddr() |
----------------------------
至于耦合,它指的是两个类/模块彼此之间的关联或依赖程度。对于低耦合类,改变一个类中的主要内容不应该影响到另一个类。高耦合会使更改和维护代码变得困难;由于类紧密地结合在一起,因此进行更改可能需要对整个系统进行改造。
好的软件设计具有高内聚性和低耦合性。
其他回答
在面向对象编程语言中,模块内部的高内聚和模块之间的低耦合通常被认为与高质量有关。
例如,每个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.
在上图中,我们可以看到,在低内聚情况下,只有一个类负责执行大量不相同的作业,这降低了可重用性和维护的机会。但是在高内聚的情况下,所有的作业都有一个单独的类来执行特定的作业,这样可以获得更好的可用性和可维护性。
内聚指的是类(或模块)可以做什么。低内聚意味着这个类会做各种各样的动作——它很宽泛,不关注它应该做什么。高内聚意味着类专注于它应该做的事情,即只有与类的意图相关的方法。
低内聚的例子:
-------------------
| Staff |
-------------------
| checkEmail() |
| sendEmail() |
| emailValidate() |
| PrintLetter() |
-------------------
高内聚的例子:
----------------------------
| Staff |
----------------------------
| -salary |
| -emailAddr |
----------------------------
| setSalary(newSalary) |
| getSalary() |
| setEmailAddr(newEmail) |
| getEmailAddr() |
----------------------------
至于耦合,它指的是两个类/模块彼此之间的关联或依赖程度。对于低耦合类,改变一个类中的主要内容不应该影响到另一个类。高耦合会使更改和维护代码变得困难;由于类紧密地结合在一起,因此进行更改可能需要对整个系统进行改造。
好的软件设计具有高内聚性和低耦合性。
理论的区别
凝聚力
内聚性是模块相对功能强度的表征。 内聚模块执行单一任务,几乎不需要与其他模块交互 程序其他部分的组件。 具有高内聚和低耦合的模块称为功能独立模块 其他模块。
衔接的分类
1.巧合2。逻辑3。时间4。程序5。沟通6。连续7。功能
耦合
耦合表示模块之间的相对依赖关系。 两个模块之间的耦合程度取决于它们的接口复杂性。
内聚性是一个模块相对功能强度的指示。
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视图:类之间连接程度的定性度量 耦合水平 内容 常见 控制 邮票 数据 程序调用 类型使用 包含或导入 外部#