高内聚松耦合的优化

optimization of high cohesion and loose coupling

我在一次技术面试中被问及项目的内聚和耦合。我广泛地解释了他们的定义,尽管我没有像他说的那样正确回答问题的第二部分。

"How could we achieve a highly cohesive and loosely coupled design in a project simultaneously and please explain how should this approach be implemented in a monolithic project ?"

我回答说这两个目标是矛盾的,所以我们需要找出每个项目或模块的最佳选择,但我无法提供全面的答案。

如果有人帮助我,我将不胜感激。

根据维基百科 (https://en.wikipedia.org/wiki/Cohesion_(computer_science))

High cohesion often correlates with loose coupling, and vice versa

所以目标是实现高内聚松耦合。 要实现它,您需要开发只做一件事的 类,将整体项目拆分成几个模块(DAO、UI、业务逻辑)并编程为一个接口,以便其他 类(或其他模块)对其他classes/modules的内部结构一无所知,只知道外部合同(interfaces/API)。

在阅读您的问题之前,我不熟悉凝聚力的概念。来自维基百科 (here):

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.

Cohesion is often contrasted with coupling, a different concept. High cohesion often correlates with loose coupling, and vice versa.

我认为您希望每个模块内部具有高内聚性,而它们之间存在松散耦合,这可以通过让模块仅通过简单的抽象接口进行通信来实现。要定义这些接口,您需要设计一个干净的关注点分离,其中所有紧密耦合的任务都在相同的 class 中完成,而任务具有不同的粒度(例如高级算法与低级实现细节)被接口分离和抽象掉。

我首先要回答的是,这与你所说的“两个定义是矛盾的”恰恰相反。我将引用 John W. Satzinger System Analysis and Design in a Changing World, Key Facts

中的一句话来描述

Low coupling often correlates with high cohesion, and vice versa


通过在 Monolithic 中说,他们向您发出信号,让您询问 SOLID 原则,如果您应用它们,结果会很高内聚和松耦合项目。

定义如下:

1.Single-责任原则(SRP)

定义: class 改变的原因不应该超过一个。

好处:

  • class
  • 中的凝聚力更强
  • 依赖性 classes、
  • 之间的耦合更松散
  • 更好的可读性
  • 复杂度较低的代码
  • 代码更易于理解和维护。

2。开闭原则(OCP)

定义:软件实体(classes、模块、函数等)应该对扩展开放,对修改关闭。

好处:

  • 松耦合,
  • 提高可读性
  • 降低破坏现有功能的风险
  • 代码可维护和可重用。
  • 代码更健壮。

3。里氏代换原则(LSP)

定义:程序中的对象应该可以用其子类型的实例替换,而不会改变该程序的正确性。

好处:

  • 松耦合
  • 代码更可重用。
  • Class层次结构简单易懂。

4。接口隔离原则(ISP)

定义:许多特定于客户端的接口优于一个通用接口

好处:

  • 解耦系统。
  • 代码易于重构。

5。依赖倒置原则(DIP)

定义:高级模块不应该依赖于低级模块,而是两者都应该依赖于抽象。抽象不应依赖于细节;而细节应该取决于抽象。

好处:

  • 高内聚。
  • 减少耦合。
  • 代码更可重用。

更多信息


书籍

  • Steve McConnell 的代码完成
  • Bob 叔叔的整洁代码