Architecture and design
引入
6:03
软件工程
软件工程让系统的寿命超越其作者。前三个单元塑造产品:需求、架构和界面设计。接下来的两个单元通过版本控制和测试守住质量。最后两个单元涉及安全、伦理和团队项目,完成整个过程。贯穿始终的项目是一个名为 BookShare 的图书共享服务,所有例子都来自这个项目,并且每个例子都经过检验。
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| layers/ˈleɪəz/ | 层 | céng |
| dependency rule/dɪˈpendənsi ruːl/ | 依赖规则 | yī lài guī zé |
| coupling/ˈkʌplɪŋ/ | 耦合 | ǒu hé |
| Cohesion/kəʊˈhiːʒn/ | 内聚 | nèi jù |
| interface/ˈɪntəfeɪs/ | 接口 | jiē kǒu |
| design pattern/dɪˈzaɪn ˈpætn/ | 设计模式 | shè jì mó shì |
| Strategy/ˈstrætədʒi/ | 策略模式 | cè lüè mó shì |
| Observer/ɒbˈzɜːvə/ | 观察者模式 | guān chá zhě mó shì |
| Repository/rɪˈpɒzɪtəri/ | 仓储模式 | cāng chǔ mó shì |
| dependency inversion/dɪˈpendənsi ɪnˈvɜːʃn/ | 依赖倒置 | yī lài dào zhì |
| Instability/ɪnstəˈbɪlɪti/ | 不稳定度 | bù wěn dìng dù |
| Law of Demeter/lɔː ɒv ˈdemiːtə/ | 迪米特法则 | dí mǐ tè fǎ zé |
依赖向内的分层
- BookShare 有三个层:表示层(网页应用)、领域层(借阅、会员、目录)和存储层(数据库)。
- 依赖规则:依赖指向内层。领域层对任何框架都一无所知,正因如此,它才易于测试。

The dependency rule points —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Domain purity is what makes it testable without browser or database.
用数量衡量耦合与内聚
- 内聚让相关改动集中在一个模块中;耦合则让改动分散开来。修改借阅上限规则会涉及 1 个模块和 2 个文件(高内聚、低耦合)。
- 如果同一规则分散到了表示层,修改就会涉及 3 层和 5 个文件。这个数量就是设计的度量指标。
- 借书时序:表示层调用
domain.borrow(member, copy);领域层检查限额和藏书副本的状态;存储层记录借阅及其日期;表示层确认。共有四个参与者、五条带标签的消息。
The loan-rule change touches 1 module, 2 files. The version spread across the layers touches —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
3 layers, 5 files: the count is the coupling metric.
Put the borrow sequence in order.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Only the domain decides whether a loan is allowed; presentation and storage just carry the request in and the record out.
边界带来的好处
- 提醒的发送由领域层拥有的
Notifier接口来隔离。领域层只调用send;它完全不需要知道消息是通过电子邮件还是推送发送的。
# domain: owns the interface
class Notifier:
def send(self, member, text): ...
# domain: no email or web imports
class LoanService:
def __init__(self, notifier):
self.notifier = notifier
def remind(self, loan):
text = loan.title + " is overdue"
self.notifier.send(loan.member, text)
# outer layer: one way to deliver
class EmailNotifier(Notifier):
def send(self, member, text):
smtp_send(member.email, text)
# the one line that changes for push
service = LoanService(EmailNotifier())
- 切换到推送只需新增一个类并修改一行代码,无需改动领域层。测试时可以传入一个只记录消息的模拟
Notifier,这样就能在没有邮件服务器的情况下测试领域层。 - 如果
LoanService自己导入电子邮件库,依赖就会指向外层,切换发送方式或在没有邮件服务器的情况下测试都会更困难。
Swapping the Notifier strategy costs —
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Behind an interface: the boundary buys the swap.
Swapping email reminders for push notifications behind the Notifier interface means editing the domain layer.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The domain calls only the interface, so the swap is a new implementation and one configuration line, with zero domain edits. That is the boundary's payoff.
模式以其应对的变化命名
- 设计模式是一种有名称的权衡。图书系统中有三种:
| 模式 | 在这里的作用…… | 使你能够…… |
|---|---|---|
| 策略模式 | 通过 Notifier 接口隔离提醒的发送方式 |
将电子邮件切换为推送 |
| 观察者模式 | 让提醒服务监听“借阅逾期”事件 | 无需修改借阅就能添加监听者 |
| 仓储模式 | 通过领域层拥有的接口隐藏存储细节 | 更换数据库 |
- 这三种模式都运用了依赖倒置:高层策略定义接口,低层细节实现接口。这就是用代码表达分层中依赖向内的规则。
Swapping email reminders for push notifications without touching the domain uses which pattern?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The delivery method is an interchangeable strategy behind the Notifier interface.
The domain layer should import the web framework to read requests directly.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
That points a dependency outward and makes the domain untestable without the framework.
用数量衡量不稳定性
- 对一个模块,统计传入依赖 $C_a$(谁使用它)和传出依赖 $C_e$(它使用什么)。不稳定性 $I = C_e/(C_a + C_e)$ 的取值从 0(所有模块都依赖它,而它不依赖任何模块)到 1。
- 领域层的不稳定性应接近 0,网页层的则应接近 1。当 $C_a = 2$ 且 $C_e = 6$ 时,$I = \mathbf{0.75}$:这个模块容易修改,而且理应如此,因为很少有其他模块依赖它。
A module with $C_a = 2$ incoming and $C_e = 6$ outgoing dependencies: instability $I$?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
$6/(2 + 6) = 0.75$.
The domain has $C_a = 6$ and $C_e = 0$: its instability?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
$0/6 = 0$: maximally stable, as the dependency rule wants.
示例:只与朋友交谈
- 这个调用依次访问了三个对象:
member.account().wallet().debit(fee)
- 现在,修改
Wallet就会导致借书代码出错。这违反了迪米特法则:只调用自身、自己的字段、参数以及自己创建的对象上的方法。 - 改为编写
member.payFee(fee),让Member将工作继续传递下去。现在调用方只依赖 1 个类,而不是 3 个类,调用链也可以在不影响调用方的情况下改变。
order.customer().address().city() follows the Law of Demeter.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
It reaches through three objects; ask order for what you need.
容易丢掉的分数
- **领域层导入框架。**这颠倒了依赖规则,还可能使核心部分更难独立测试。
- **箭头没有标签。**依赖没有标注的图无法让审查者检查依赖关系。
- **为了使用模式而使用模式。**每种模式都应对一种变化;如果没有这种变化,它就只是多余的代码。
回顾
- 表示层、领域层、存储层:依赖指向内层。
- 内聚使一项改动集中在一个模块中:涉及 $1$ 个模块和 $2$ 个文件,而不是 $3$ 层和 $5$ 个文件。
- 边界接口使切换只需修改一行配置。
出了什么问题?只有网站团队能看到这些信息。