Skip to Content
先整理?
book

先整理?

by Kent Beck
May 2025
Intermediate to advanced
124 pages
1h 7m
Chinese
O'Reilly Media, Inc.
Content preview from 先整理?

第 32 章 凝聚力 凝聚力

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

耦合元素应该是同一包含元素的子元素。 这是内聚的第一个含义。把所有的粪便铲到一堆里。内聚的第二个含义是:,不是粪便的元素(好吧,不是耦合的元素)应该去别的地方。

例如,假设我们有一个包含 10 个函数的模块。其中三个函数是耦合的。其他七个该去哪里呢?我们有两种选择(图 32-1)。

tifi 3201
图 32-1. 通过(上图)提取内聚子元素或(下图)将未耦合子元素移至别处来改善不粘连元素

第一种方法是将耦合元素捆绑到自己的子元素中。我们可以创建一个只包含三个函数的子模块。这个子模块将是内聚的,因为它的元素是耦合的。原始模块的内聚性可能会降低,因为现在它的元素都不是耦合的,但我们的情况不会比以前更糟。

提取辅助函数就是这种 "提取内聚子元素 "的方法。如果辅助函数的各行必须一起更改,那么辅助函数就是内聚的,内聚带来的好处有:更容易分析、更容易更改、不易发生意外行为更改。

第二种选择是将未耦合的元素放到其他地方。放在哪里?这就是设计师的职责所在。这些功能与什么耦合?将这些函数移到离它们的兄弟姐妹更近的地方。它们是相互耦合的吗?为它们创建另一个子模块。

不要轻举妄动。您正在使用不完整且不断变化的信息,了解什么与什么相耦合。不要大幅度地重新排列所有元素。一次只移动一个元素。为下一个人整理代码。如果每个人都遵守童子军规则("让它比你发现它时更好"),随着时间的推移,代码就会变得更适合使用。

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

超越Vibe编程

超越Vibe编程

Addy Osmani
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9798341656949