Last active 1778296293

WangJerome's Avatar WangJerome revised this gist 1778296293. Go to revision

1 file changed, 630 insertions

DDD-CQRS-Clean-Architecture-Combined.md(file created)

@@ -0,0 +1,630 @@
1 + # 在 Go 中结合 DDD、CQRS 和整洁架构 (Clean Architecture)
2 +
3 + * **Robert Laszczak** (Three Dots Labs 联合创始人,Watermill 的创造者,《Go With The Domain》的作者)
4 +
5 + 在[之前的文章](https://threedots.tech/series/modern-business-software-in-go/)中,我们介绍了诸如 **DDD 精简版 (DDD Lite)**、**CQRS** 和**整洁(六边形)架构 (Clean/Hexagonal Architecture)** 等技术。即使单独使用,它们也各有益处。但它们结合在一起时效果最佳——就像“超凡战队 (Power Rangers)”一样。遗憾地是,在真实项目中将它们结合在一起并不简单。 **在这篇文章中,我将向你展示如何以最实用、最高效的方式将 DDD 精简版、CQRS 和整洁架构连接在一起。**
6 +
7 + ### 我为什么要关心这个?
8 +
9 + 从事编程项目类似于规划和建造一个住宅区。如果你知道这个区域在不久的将来会扩张,你需要为未来的改进留出空间。即使在开始时,这看起来像是浪费空间。你应该为未来的设施,如住宅楼、医院和寺庙预留空间。**如果不这样做,你将不得不清理现有的建筑和街道,以为新的腾出空间。** 最好早点考虑这一点。
10 +
11 + ![Empty district](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/district-empty_hu220d4ff6c72c1d6020e531f239fbe9c2_271317_2000x1083_resize_q80_h2_lanczos_3.webp)
12 +
13 + 代码的情况也是如此。如果你知道项目将开发超过一个月,你应该从一开始就考虑到长期目标。**你需要以不会阻碍未来工作的方式来编写代码。即使起初它看起来像是过度设计以及大量的样板代码,你也必须考虑长远利益。**
14 +
15 + 这并不意味着你需要规划未来要实施的所有功能——恰恰相反。这种方法帮助你适应新的需求或是对业务领域理解的改变。这里不需要大规模的前置设计 (Big upfront design)。在当下,世界变化迅速,无法适应的公司将很快倒闭,这一点至关重要。
16 +
17 + ![Full district](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/district-full_hu4591c93297b951538442105f8fe9960b_269516_2000x1083_resize_q80_h2_lanczos_3.webp)
18 +
19 + **这正是当你结合这些模式时它们带给你的:保持持续开发速度的能力,而无需破坏或过多触碰现有代码。**
20 +
21 + 这需要更多的思考和规划吗?这是一种更具挑战性的方式吗?你需要拥有额外的知识才能做到吗?当然!**但长期的结果值得这样做!** 幸运的是,你来对地方了。 😉
22 +
23 + 让我们把理论抛在脑后。让我们开始写代码。在这篇文章中,我们将跳过对设计选择的推理。这些我们在[之前的文章](https://threedots.tech/series/modern-business-software-in-go/)中已经描述过。如果你还没有读过,我建议你阅读——你会更好地理解这篇文章。
24 +
25 + 如同之前的文章,我们将基于重构一个真实的开源项目来构建我们的代码。这应该使示例更加真实,并适用于你自己的项目。
26 +
27 + 准备好了吗?
28 +
29 + 注意
30 +
31 + #### 这不仅仅是又一篇充斥着随机代码片段的文章。
32 +
33 + 这篇文章是我们更大系列的一部分,在该系列中,我们展示如何构建**易于开发、维护并在长期内令人愉快的工作的 Go 应用程序。** 我们通过分享基于许多我们带领团队进行的实验以及[科学研究](https://threedots.tech/post/ddd-lite-in-go-introduction/?utm_source=about-wild-workouts#thats-great-but-do-you-have-any-evidence-it-works)证明的技术来实现这一目标。
34 +
35 + 你可以通过与我们一起构建一个[完全功能性的](https://threedots.tech/post/serverless-cloud-run-firebase-modern-go-application/?utm_source=about-wild-workouts#what-wild-workouts-can-do)示例 Go Web 应用程序 —— **Wild Workouts** 来学习这些模式。
36 +
37 + 我们做了一件不同的事——**我们在初始的 Wild Workouts 实现中加入了一些细微的问题**。是我们疯了吗?还没有。 😉 这些问题在 Go 项目中很常见。**从长远来看,这些小的问题会变得至关重要并阻止添加新功能。**
38 +
39 + **这正是一名高级或主管开发人员的基本技能之一;你总是需要记住长期的影响。**
40 +
41 + 我们将通过 **重构** Wild Workouts 来修复这些问题。这样,你将快速理解我们分享的技术。
42 +
43 + 你是否知道那种感觉:读完一篇关于某项技术的文章后,试图只因为指南中跳过了一些问题而受阻?省略这些细节使文章更短并增加了页面浏览量,但这不是我们的目标。我们的目标是创建提供足够相关知识的应用教程。如果你还没有阅读[系列中的之前的文章](https://threedots.tech/series/modern-business-software-in-go/?utm_source=about-wild-workouts),我们强烈建议你去看看。
44 +
45 + 我们认为在某些领域没有捷径。如果你想以快速高效的方式构建复杂的应用程序,你需要花时间学习。如果这很简单,我们就不会有大量令人恐惧的遗留代码。
46 +
47 + 这是目前发布的 **[14 篇文章的完整列表](https://threedots.tech/series/modern-business-software-in-go/?utm_source=about-wild-workouts)**。
48 +
49 + **Wild Workouts 的完整源代码** 可以在 [GitHub](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example?utm_source=about-wild-workouts) 上找到。别忘了给我们的项目点个 Star!⭐
50 +
51 + ### 让我们开始重构
52 +
53 + 让我们从 [领域优先 (Domain-First)](https://threedots.tech/post/ddd-lite-in-go-introduction/#domain-first-approach) 方法开始我们的重构。我们将从引入 [领域层 (domain layer)](https://threedots.tech/post/introducing-clean-architecture/#the-dependency-inversion-principle) 开始。这可以确保实现细节不会影响我们的领域代码。**我们还可以将所有精力投入到理解业务问题,而不是编写枯燥的数据库查询和 API 端点。**
54 +
55 + 领域优先方法既适用于救援(重构 😉)也适用于从零开始 (greenfield) 的项目。
56 +
57 + 为了开始构建我的领域层,我需要确定应用程序实际上在做什么。本文将重点介绍 Wild Workouts 微服务 `trainings` 的重构([github.com/tree.../internal/trainings](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/tree/v2.5/internal/trainings))。我首先通过识别应用程序处理用例来开始工作。在此之前对 [整洁架构](https://threedots.tech/post/introducing-clean-architecture/) 的重构后,你可以在 [`TrainingService`](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/v2.4/internal/trainings/app/training_service.go#L32) 中找到它。当我使用混乱的应用程序工作时,我会查看 RPC 和 HTTP 端点以找到支持的用例。
58 +
59 + 我识别出的功能之一是**培训改期审批**。在 Wild Workouts 中,如果改期请求是在培训日期前不到 24 小时提出的,则需要进行培训改期审批。如果学员请求改期,培训师需要批准。如果培训师请求改期,学员需要接受。
60 +
61 + ```go
62 + func (c TrainingService) ApproveTrainingReschedule(ctx context.Context, user auth.User, trainingUUID string) error {
63 + return c.repo.ApproveTrainingReschedule(ctx, trainingUUID, func(training Training) (Training, error) {
64 + // 检查是否有提议的新时间
65 + if training.ProposedTime == nil {
66 + return Training{}, errors.New("training has no proposed time")
67 + }
68 + // 检查是否有提议改期的用户类型
69 + if training.MoveProposedBy == nil {
70 + return Training{}, errors.New("training has no MoveProposedBy")
71 + }
72 + // 如果是培训师提议的,则学员需要审批
73 + if *training.MoveProposedBy == "trainer" && training.UserUUID != user.UUID {
74 + return Training{}, errors.Errorf("user '%s' cannot approve reschedule of user '%s'", user.UUID, training.UserUUID)
75 + }
76 + // 请求改期的人不能自己审批
77 + if *training.MoveProposedBy == user.Role {
78 + return Training{}, errors.New("reschedule cannot be accepted by requesting person")
79 + }
80 +
81 + // 更新培训时间
82 + training.Time = *training.ProposedTime
83 + training.ProposedTime = nil
84 +
85 + return training, nil
86 + })
87 + }
88 + ```
89 +
90 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63)
91 +
92 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63)
93 +
94 + ### 从领域开始
95 +
96 + 即使这看起来并非你最见过的最糟糕的代码,函数如 `ApproveTrainingReschedule` 随时间推移往往会变得更复杂。更复杂的函数意味着未来开发中更多的潜在错误。
97 +
98 + 如果你是新项目的新手,并且缺乏关于该项目的_“萨满知识”_(shaman knowledge,指对底层历史逻辑的理解),这更有可能发生。**你应该始终考虑将来会参与项目的每一个人,并使你的代码抵抗被他们无意中打破的风险。** 这将帮助你的项目避免变成大家都不敢触碰的遗留代码。你可能知道当你对一个项目陌生时,因为害怕破坏系统而对什么都畏手畏脚的感觉。
99 +
100 + 人们换工作的频率超过每两年一次的频率并不少见。这使得对于项目的长期开发变得更加关键。
101 +
102 + 如果你不相信这段代码会变得更复杂,我建议你查看你在最糟糕的项目位置的 Git 历史记录。在大多数情况下,最糟糕的代码始于_"只是一两个简单的 if"_。 😉 代码越复杂,后续简化就越困难。**我们应该对日益增加的复杂性保持敏感,并尽快尝试简化它们。**
103 +
104 + #### `Training` 领域实体 (Entity)
105 +
106 + 在分析当前由 `trainings` 微服务处理的使用例时,我发现它们都与一个_课程/培训 (training)_有关。自然地,创建一个 `Training` 类型来处理这些操作。
107 +
108 + ![Service methods](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/training-svc-methods_hu23e5b80bfce1cbb76338ba1eb2a6298a_91843_833x288_resize_q80_h2_lanczos.webp)
109 +
110 + 重构后的 [TrainingService](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/v2.4/internal/trainings/app/training_service.go#L32) 方法
111 +
112 + 注意
113 +
114 + #### 名词 == 实体
115 +
116 + 这是一种有效发现实体的方法吗?嗯,其实不是。
117 +
118 + DDD 提供了帮助我们建立复杂领域模型而无需猜测的工具(_战略 DDD 模式_, _聚合 (Aggregates)_)。我们不希望猜测我们的聚合是什么样子的——我们需要工具来发现它们。事件风暴 (Event Storming) 技术在这里非常有用……但这将是另一整篇文章的话题。
119 +
120 + 这个话题足够复杂,值得写几篇文章。这也是我们稍后要做的事情。 😉
121 +
122 + 这是否意味着你不应该在没有战略 DDD 模式的情况下使用这些技术?当然不是!当前的方法对于较简单的项目可能足够好。不幸的是(或者幸运的是 😉),并非所有项目都是简单的。
123 +
124 + ```go
125 + package training
126 +
127 + // ...
128 +
129 + type Training struct {
130 + uuid string
131 +
132 + userUUID string
133 + userName string
134 +
135 + time time.Time
136 + notes string
137 +
138 + proposedNewTime time.Time
139 + moveProposedBy UserType // 提议改期的用户类型 (Trainer/Attendee)
140 +
141 + canceled bool // 是否已取消
142 + }
143 + ```
144 +
145 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L10)
146 +
147 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L10)
148 +
149 + 所有字段都是私有的,以提供封装。这对于满足关于 DDD 精简版文章中的 [“始终在内存中保持有效状态”](https://threedots.tech/post/ddd-lite-in-go-introduction/#the-second-rule-always-keep-a-valid-state-in-the-memory) 规则至关重要。
150 +
151 + 得益于构造函数中的验证和封装的字段,我们可以确保 `Training` 始终是有效的。**现在,对 project 一无所知的人无法以错误的方式使用它。**
152 +
153 + 同样的规则适用于 `Training` 提供的任何方法。
154 +
155 + ```go
156 + package training
157 +
158 + func NewTraining(uuid string, userUUID string, userName string, trainingTime time.Time) (*Training, error) {
159 + if uuid == "" {
160 + return nil, errors.New("empty training uuid")
161 + }
162 + if userUUID == "" {
163 + return nil, errors.New("empty userUUID")
164 + }
165 + if userName == "" {
166 + return nil, errors.New("empty userName")
167 + }
168 + if trainingTime.IsZero() {
169 + return nil, errors.New("zero training time")
170 + }
171 +
172 + return &Training{
173 + uuid: uuid,
174 + userUUID: userUUID,
175 + userName: userName,
176 + time: trainingTime,
177 + }, nil
178 + }
179 + ```
180 +
181 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L25)
182 +
183 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L25)
184 +
185 + #### 在领域层审批改期
186 +
187 + 如 [DDD 精简版介绍](https://threedots.tech/post/ddd-lite-in-go-introduction/#the-first-rule---reflect-your-business-logic-literally) 中所述,我们使用基于行为而非数据的面向行为的方法来构建我们的领域。让我们在领域实体上对 `ApproveReschedule` (审批改期) 进行建模。
188 +
189 + ```go
190 + package training
191 +
192 + // ...
193 +
194 + func (t *Training) IsRescheduleProposed() bool {
195 + // 检查是否有提议改期的用户类型和新时间
196 + return !t.moveProposedBy.IsZero() && !t.proposedNewTime.IsZero()
197 + }
198 +
199 + var ErrNoRescheduleRequested = errors.New("no training reschedule was requested yet")
200 +
201 + func (t *Training) ApproveReschedule(userType UserType) error {
202 + // 如果没有提出改期请求,则不允许审批
203 + if !t.IsRescheduleProposed() {
204 + return errors.WithStack(ErrNoRescheduleRequested)
205 + }
206 +
207 + // 如果是提议改期的同一用户类型,则不能审批
208 + if t.moveProposedBy == userType {
209 + return errors.Errorf(
210 + "trying to approve reschedule by the same user type which proposed reschedule (%s)",
211 + userType.String(),
212 + )
213 + }
214 +
215 + // 更新正式时间
216 + t.time = t.proposedNewTime
217 +
218 + // 重置提议的时间
219 + t.proposedNewTime = time.Time{}
220 + t.moveProposedBy = UserType{}
221 +
222 + return nil
223 + }
224 + ```
225 +
226 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/reschedule.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/reschedule.go#L47)
227 +
228 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/reschedule.go#L47)
229 +
230 + 如果你还没有机会阅读:
231 +
232 + * [DDD 精简版介绍](https://threedots.tech/post/ddd-lite-in-go-introduction/),
233 + * [引入整洁架构](https://threedots.tech/post/introducing-clean-architecture/),
234 + * [引入基础 CQRS](https://threedots.tech/post/basic-cqrs-in-go/),
235 + * [仓储模式](https://threedots.tech/post/repository-pattern-in-go/)。
236 +
237 + 我强烈建议你检查它们。它们将帮助你更好地理解这篇文章。它们解释了我们将在这篇文章中结合的决策和技术。
238 +
239 + ### 用命令编排
240 +
241 + 现在,应用层 (application layer) 可以只负责流程的编排。那里没有领域逻辑。**我们将所有的业务复杂性隐藏在领域层中。这正是我们的目标。**
242 +
243 + 为了获取和保存培训,我们使用 [仓储模式 (Repository Pattern)](https://threedots.tech/post/repository-pattern-in-go/)。
244 +
245 + ```go
246 + package command
247 +
248 + // ...
249 +
250 + func (h ApproveTrainingRescheduleHandler) Handle(ctx context.Context, cmd ApproveTrainingReschedule) (err error) {
251 + defer func() {
252 + logs.LogCommandExecution("ApproveTrainingReschedule", cmd, err)
253 + }()
254 +
255 + // 调用仓库更新培训
256 + return h.repo.UpdateTraining(
257 + ctx,
258 + cmd.TrainingUUID,
259 + cmd.User,
260 + func(ctx context.Context, tr *training.Training) (*training.Training, error) {
261 + originalTrainingTime := tr.Time()
262 +
263 + // 调用领域方法执行审批逻辑
264 + if err := tr.ApproveReschedule(cmd.User.Type()); err != nil {
265 + return nil, err
266 + }
267 +
268 + // 通知培训师服务进行实际的培训更新
269 + err := h.trainerService.MoveTraining(ctx, tr.Time(), originalTrainingTime)
270 + if err != nil {
271 + return nil, err
272 + }
273 +
274 + return tr, nil
275 + },
276 + )
277 + }
278 + ```
279 +
280 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/app/command/approve_training_reschedule.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/approve_training_reschedule.go#L39)
281 +
282 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/approve_training_reschedule.go#L39)
283 +
284 + ### 重构培训取消逻辑 (Cancelation)
285 +
286 + 现在让我们看看 `TrainingService` 中的 `CancelTraining`。
287 +
288 + 领域逻辑很简单:你可以在培训日期前 24 小时取消培训。如果在培训前不到 24 小时而你想取消:
289 +
290 + * 如果你是培训师,学员将“找回”他们的课程,外加一次额外的课程(没有人喜欢在同一天改变计划!)
291 + * 如果你是学员,你将失去这次课程
292 +
293 + 当前实现的样子如下:
294 +
295 + ```go
296 + func (c TrainingService) CancelTraining(ctx context.Context, user auth.User, trainingUUID string) error {
297 + return c.repo.CancelTraining(ctx, trainingUUID, func(training Training) error {
298 + // 权限检查
299 + if user.Role != "trainer" && training.UserUUID != user.UUID {
300 + return errors.Errorf("user '%s' is trying to cancel training of user '%s'", user.UUID, training.UserUUID)
301 + }
302 +
303 + var trainingBalanceDelta int // 课程余额的变化量
304 +
305 + if training.CanBeCancelled() {
306 + // 直接退还课程
307 + trainingBalanceDelta = 1
308 + } else {
309 + if user.Role == "trainer" {
310 + // 取消的课程+1 培训师不足24小时取消的“罚款”
311 + trainingBalanceDelta = 2
312 + } else {
313 + // 不足24小时取消课程的“罚款”
314 + trainerBalanceDelta = 0
315 + }
316 + }
317 +
318 + if trainingBalanceDelta != 0 {
319 + err := c.userService.UpdateTrainingBalance(ctx, training.UserUUID, trainingBalanceDelta)
320 + if err != nil {
321 + return errors.Wrap(err, "unable to change trainings balance")
322 + }
323 + }
324 +
325 + err := c.trainerService.CancelTraining(ctx, training.Time)
326 + if err != nil {
327 + return errors.Wrap(err, "unable to cancel training")
328 + }
329 +
330 + return nil
331 + })
332 + }
333 + ```
334 +
335 + 你可以看到在取消期间计算课程余额差的某种“算法”。这在应用层中不是一个好兆头。
336 +
337 + 像这样的逻辑应该存在于我们的领域层中。**如果你在应用层中开始看到与逻辑相关的 `if` 语句,你应该考虑如何将其移动到领域层。** 这将更容易在其他地方进行测试和重用。
338 +
339 + 这取决于项目,但通常**领域逻辑在初始开发后相当稳定,可以长期保持不变得存在**。它可以经受住服务之间、框架更改、库更改和 API 更改的迁移。得益于这种分离,我们可以以更安全、更快的速度进行所有这些更改。
340 +
341 + 让我们将 `CancelTraining` 方法分解为多个分离的部分。这将允许我们独立地测试和更改它们。
342 +
343 + 首先,我们需要处理取消逻辑并将 `Training` 标记为已取消。
344 +
345 + ```go
346 + package training
347 +
348 + func (t Training) CanBeCanceledForFree() bool {
349 + return t.time.Sub(time.Now()) >= time.Hour*24
350 + }
351 +
352 + var ErrTrainingAlreadyCanceled = errors.New("training is already canceled")
353 +
354 + func (t *Training) Cancel() error {
355 + if t.IsCanceled() {
356 + return ErrTrainingAlreadyCanceled
357 + }
358 +
359 + t.canceled = true
360 + return nil
361 + }
362 + ```
363 +
364 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go#L14)
365 +
366 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go#L14)
367 +
368 + 这里没有什么复杂的。那很好!
369 +
370 + 需要移动的第二个部分是取消后计算课程余额的“算法”。在理论上,我们可以将其放在 `Cancel()` 方法中,但在我看来,这会打破[单一职责原则](https://en.wikipedia.org/wiki/Single-responsibility_principle)和 [CQS](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation)。而且我喜欢简短的函数。
371 +
372 + 但我们应该把它放在哪里?某个对象?领域服务?在一些以 _J_ 开头并以 _ava_ 结尾的语言中(指 Java),这样是有意义的。但在 Go 中,简单地创建一个函数就足够了。
373 +
374 + ```go
375 + package training
376 +
377 + // CancelBalanceDelta 返回在取消培训后应该调整的课时余额变化量。
378 + func CancelBalanceDelta(tr Training, cancelingUserType UserType) int {
379 + if tr.CanBeCanceledForFree() {
380 + // 只是退还课程
381 + return 1
382 + }
383 +
384 + switch cancelingUserType {
385 + case Trainer:
386 + // 1 用于取消的课程 +1 作为培训师在培训前不到 24 小时取消的“罚款”
387 + return 2
388 + case Attendee:
389 + // 作为在培训前不到 24 小时取消的“罚款”
390 + return 0
391 + default:
392 + panic(fmt.Sprintf("not supported user type %s", cancelingUserType))
393 + }
394 + }
395 + ```
396 +
397 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel_balance.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/cancel_balance.go#L6)
398 +
399 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/cancel_balance.go#L6)
400 +
401 + 代码现在很直白。**我可以想象,我可以坐下来与任何非技术人员一起浏览这段代码,解释它是如何工作的。**
402 +
403 + 那测试呢?这可能会有点争议,但在我看来,这里的测试是多余的。测试代码将复制函数的实现。算法中的任何更改都将需要复制逻辑到测试中。我不会在这里编写测试,但如果你能因此睡个好觉——为什么不呢!
404 +
405 + #### 移动 CancelTraining 到命令处理器
406 +
407 + 我们的领域已经准备好了,所以现在让我们使用它。我们将以与之前相同的方式做到这一点:
408 +
409 + 1. 从仓库获取实体,
410 + 2. 编排领域事情,
411 + 3. 调用外部 `trainer` 服务来取消培训(该服务是“培训师日历”的真值来源),
412 + 4. 返回实体以保存到数据库。
413 +
414 + ```go
415 + package command
416 +
417 + // ...
418 +
419 + func (h CancelTrainingHandler) Handle(ctx context.Context, cmd CancelTraining) (err error) {
420 + defer func() {
421 + logs.LogCommandExecution("CancelTrainingHandler", cmd, err)
422 + }()
423 +
424 + return h.repo.UpdateTraining(
425 + ctx,
426 + cmd.TrainingUUID,
427 + cmd.User,
428 + func(ctx context.Context, tr *training.Training) (*training.Training, error) {
429 + // 1. 执行领域取消逻辑
430 + if err := tr.Cancel(); err != nil {
431 + return nil, err
432 + }
433 +
434 + // 2. 计算余额变化(如果需要)
435 + if balanceDelta := training.CancelBalanceDelta(*tr, cmd.User.Type()); balanceDelta != 0 {
436 + err := h.userService.UpdateTrainingBalance(ctx, tr.UserUUID(), balanceDelta)
437 + if err != nil {
438 + return nil, errors.Wrap(err, "unable to change trainings balance")
439 + }
440 + }
441 +
442 + // 3. 调用外部服务取消实际日程
443 + if err := h.trainerService.CancelTraining(ctx, tr.Time()); err != nil {
444 + return nil, errors.Wrap(err, "unable to cancel training")
445 + }
446 +
447 + return tr, nil
448 + },
449 + )
450 + }
451 + ```
452 +
453 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/app/command/cancel_training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/cancel_training.go#L36)
454 +
455 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/cancel_training.go#L36)
456 +
457 + ### 仓储重构
458 +
459 + 最初的仓储实现非常棘手,因为我为每个用例都使用了自定义方法。
460 +
461 + ```go
462 + type trainingRepository interface {
463 + FindTrainingsForUser(ctx context.Context, user auth.User) ([]Training, error)
464 + AllTrainings(ctx context.Context) ([]Training, error)
465 + CreateTraining(ctx context.Context, training Training, createFn func() error) error
466 + CancelTraining(ctx context.Context, trainingUUID string, deleteFn func(Training) error) error
467 + RescheduleTraining(ctx context.Context, trainingUUID string, newTime time.Time, updateFn func(Training) (Training, error)) error
468 + ApproveTrainingReschedule(ctx context.Context, trainingUUID string, updateFn func(Training) (Training, error)) error
469 + RejectTrainingReschedule(ctx context.Context, trainingUUID string, updateFn func(Training) (Training, error)) error
470 + }
471 + ```
472 +
473 + 得益于引入 `training.Training` 实体,我们可以有一个简单得多的版本:一个用于添加新培训,一个用于更新。
474 +
475 + ```go
476 + package training
477 +
478 + // ...
479 +
480 + type Repository interface {
481 + AddTraining(ctx context.Context, tr *Training) error
482 +
483 + GetTraining(ctx context.Context, trainingUUID string, user User) (*Training, error)
484 +
485 + UpdateTraining(
486 + ctx context.Context,
487 + trainingUUID string,
488 + user User,
489 + updateFn func(ctx context.Context, tr *Training) (*Training, error),
490 + ) error
491 + }
492 + ```
493 +
494 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/repository.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/repository.go#L16)
495 +
496 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/repository.go#L16)
497 +
498 + 如 [上一篇文章](https://threedots.tech/post/repository-pattern-in-go/) 中所述,我们使用 Firestore 实现了我们的仓储。我们也将在此实现中使用 Firestore。请记住,这是一个实现细节——你可以使用任何你想要的数据库。在上一篇文章中,我们展示了使用不同数据库的示例实现。
499 +
500 + ```go
501 + package adapters
502 +
503 + // ...
504 +
505 + func (r TrainingsFirestoreRepository) UpdateTraining(
506 + ctx context.Context,
507 + trainingUUID string,
508 + user training.User,
509 + updateFn func(ctx context.Context, tr *training.Training) (*training.Training, error),
510 + ) error {
511 + trainingsCollection := r.trainingsCollection()
512 +
513 + // 使用 Firestore 事务确保原子性更新
514 + return r.firestoreClient.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
515 + documentRef := trainingsCollection.Doc(trainingUUID)
516 +
517 + firestoreTraining, err := tx.Get(documentRef)
518 + if err != nil {
519 + return errors.Wrap(err, "unable to get actual docs")
520 + }
521 +
522 + tr, err := r.unmarshalTraining(firestoreTraining)
523 + if err != nil {
524 + return err
525 + }
526 +
527 + // 权限检查
528 + if err := training.CanUserSeeTraining(user, *tr); err != nil {
529 + return err
530 + }
531 +
532 + // 调用传入的函数执行领域变更
533 + updatedTraining, err := updateFn(ctx, tr)
534 + if err != nil {
535 + return err
536 + }
537 +
538 + return tx.Set(documentRef, r.marshalTraining(updatedTraining))
539 + })
540 + }
541 + ```
542 +
543 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/adapters/trainings_firestore_repository.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/adapters/trainings_firestore_repository.go#L83)
544 +
545 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/adapters/trainings_firestore_repository.go#L83)
546 +
547 + ### 连接一切
548 +
549 + 我们现在如何使用我们的代码?我们的端口层 (ports layer) 呢?得益于 Miłosz 在 [重构到整洁架构](https://threedots.tech/post/introducing-clean-architecture/) 文章中做的重构,我们的端口层与其他层隔离。因此,在这次重构之后,它几乎不需要重大更改。我们只需调用应用命令而不是应用服务。
550 +
551 + ![Clean Architecture](https://threedots.tech/media/introducing-clean-architecture/clean-arch-2_hua2fbaee330357286a5d6d11d974a364a_220043_2000x2000_resize_q80_h2_lanczos.webp)
552 +
553 + 整洁/六边形架构层。
554 +
555 + ```go
556 + package ports
557 +
558 + // ...
559 +
560 + type HttpServer struct {
561 + app app.Application
562 + }
563 +
564 + // ...
565 +
566 + func (h HttpServer) CancelTraining(w http.ResponseWriter, r *http.Request) {
567 + trainingUUID := r.Context().Value("trainingUUID").(string)
568 +
569 + user, err := newDomainUserFromAuthUser(r.Context())
570 + if err != nil {
571 + httperr.RespondWithSlugError(err, w, r)
572 + return
573 + }
574 +
575 + // 直接调用命令处理器
576 + err = h.app.Commands.CancelTraining.Handle(r.Context(), command.CancelTraining{
577 + TrainingUUID: trainingUUID,
578 + User: user,
579 + })
580 + if err != nil {
581 + httperr.RespondWithSlugError(err, w, r)
582 + return
583 + }
584 + }
585 + ```
586 +
587 + 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/ports/http.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/ports/http.go#L87)
588 +
589 + [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/ports/http.go#L87)
590 +
591 + ### 如何在真实项目中处理此类重构?
592 +
593 + 你可能不清楚如何在真实项目中执行此类重构。这在团队中很难进行代码审查并就此重构方向达成一致。
594 +
595 + 根据我的经验,最好的方法是[结对编程 (Pair)](https://en.wikipedia.org/wiki/Pair_programming) 或[群聚编程 (Mob)](https://en.wikipedia.org/wiki/Mob_programming)。即使在起初你觉得这浪费时间,知识共享和即时审查将在未来节省大量时间。由于出色的知识共享,在项目或重构后的初始阶段后,你可以工作得更快。
596 +
597 + 在这种情况下,不要考虑为 Mob/Pair 编程“丧失”了时间。你应该考虑如果不这样做你可能会失去的时间。它还将帮助你更快地完成重构,因为你不需要等待决策。你可以立即就它们达成一致。
598 +
599 + Mob 和结对编程在实施复杂的、从零开始 (greenfield) 的项目时也非常有效。在这种情况下,知识共享尤其是一项重要的投资。我曾多次目睹这种方法如何使团队在长期内快速推进项目。
600 +
601 + 当你进行重构时,一致同意合理的时间盒也非常关键。**并且坚持它们。** 当你花费整整一个月的时间来重构而改进不明显时,你很快就会失去利益相关者的信任。快速集成和部署你的重构工作也至关重要。理想情况下,是每天一次(如果你能完成非重构工作,我相信你也可以完成重构工作!)。如果你的更改长时间未合并且未部署,会增加破坏功能的风险。它还会阻止任何在重构服务中的工作,或使更改更难合并(通常不可能在所有其他开发周围停止)。
602 +
603 + 但你如何知道项目的复杂程度是否足以使用群聚编程?不幸的是,没有魔法公式可以解答。但有一些问题你应该问自己:
604 +
605 + * 我们理解该领域吗?
606 + * 我们知道如何实现它吗?
607 + * 这最终会产生一个没有人能够审查的庞大拉取请求吗?
608 + * 如果不进行 Mob/结对编程而在知识共享上冒险,后果我们能承受吗?
609 +
610 + ### 总结
611 +
612 + 我们来到了结尾。 😄
613 +
614 + 本次重构的完整更改可以在我们的 [Wild Workouts GitHub](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63) 上找到(注意,这非常庞大!)。
615 +
616 + 如果你还没有机会阅读[之前的文章](series/modern-business-software-in-go/),你知道该怎么做了!即使其中一些使用的方法是简化的,你也应该能够在你的项目中使用它们并看到价值。
617 +
618 + 我希望在这篇文章之后,你也看到了所有引入的模式是如何很好地协同工作的。如果还没有,别担心。**我花了三年时间才将所有细节连接起来。** 但时间花得值。当我的团队和我了解了所有的连接方式后,我开始以完全不同的方式看待新项目。这使我能够以更高效的长期方式工作。
619 +
620 + 值得一提的是,就像所有技术一样,这种组合不是万能灵药。如果你正在创建一个并不复杂且在开发一个月后很久都不会被涉及的项目,可能只需将一切放在一个 `main` 包中就足够了。 😉 只是记住,当那一个月的开发变成一年时该怎么做!
621 +
622 + 我们还将在此后的文章中继续这些主题。我们将很快转向 _战略 DDD 模式 (Strategic DDD Patterns)_,这应该也能帮助你从更高层面看待你的项目。
623 +
624 + 这篇文章是否帮助你理解了如何将 DDD、整洁架构和 CQRS 结合在一起?还有什么不清楚的地方吗?请在评论中告诉我们!我们很乐意讨论你的所有问题!
625 +
626 + 你喜欢这篇文章吗?
627 + --------------------------
628 +
629 + 我们创作了大量新的有用内容。当新帖子出现时,我们可以通知你。你的电子邮件是安全的,不会分享给任何人。 🔒
630 + 你还将收到免费的 ["Go With The Domain" 电子书](https://threedots.tech/go-with-the-domain/)!
Newer Older