# 遗留代码

**遗留代码**（Legacy code）是指团队在修改的同时还必须让它继续运行的既有源代码，软件工程领域通常将其定义为没有自动化测试的代码。这个说法早于上述定义：在业界用法中，它长期是俚语，指开发者看不懂、难以修改的代码；而传统词典义则指从他人手中或项目早期阶段继承来的代码。<sup>[1](https://ptgmedia.pearsoncmg.com/images/9780131177055/samplepages/0131177052.pdf)</sup>

| 关键事实 | 详情 |
|---|---|
| 影响深远的定义 | “在我看来，遗留代码就是没有测试的代码”（迈克尔·费瑟斯，《修改代码的艺术》前言，第 xvi 页）<sup>[1](https://ptgmedia.pearsoncmg.com/images/9780131177055/samplepages/0131177052.pdf)</sup> |
| 该定义的出处 | 《修改代码的艺术》，普林蒂斯·霍尔（Prentice Hall）2004 年出版<sup>[2](https://www.pearson.com/en-us/subject-catalog/p/working-effectively-with-legacy-code/P200000008984)</sup> |
| 核心机制 | 接缝是这样一个位置：你可以在不修改该处代码的前提下改变代码的行为；其种类包括预处理接缝、链接接缝和多态接缝<sup>[3](https://mike-bland.com/2023/08/23/legacy-code-seams-and-the-most-important-design-guideline.html)</sup> |
| 安全技术 | 特征测试记录代码当前的行为，而不是它应该有的行为，从而在重构之前给出一个基线<sup>[4](https://techleadjournal.dev/episodes/195/)</sup> |
| 现代化模式 | 绞杀榕模式由马丁·福勒提出，通过在遗留系统周围构建新应用来逐步替换它<sup>[5](https://martinfowler.com/bliki/StranglerFigApplication.html)</sup> |
| 报告的成本 | 企业报告每年因过时技术损失约 3.7 亿美元，其中约 1.34 亿美元来自遗留系统改造项目，约 5600 万美元来自遗留系统维护<sup>[6](https://www.itpro.com/business/digital-transformation/it-leaders-are-throwing-money-away-with-legacy-systems-enterprises-report-usd370-million-in-losses-each-year-due-to-outdated-tech)</sup> |
| 工程负担 | 约 55% 的受访团队将 20%–40% 的工程产能用于处理技术债务<sup>[7](https://kpmg.com/kpmg-us/content/dam/kpmg/pdf/2025/technology-sector-ma-survey.pdf)</sup> |

## 定义

严格意义上的传统定义把遗留代码视为团队从别人那里得来的代码，例如通过收购获得，或因原始开发者离职而留下。在程序员的行话里，这个词的分量更重：结构纠缠不清、必须修改却无人理解、团队早已厌烦透顶的代码库。软件顾问兼作家迈克尔·费瑟斯在《修改代码的艺术》前言中提出，这种看法没有抓住要害，因为代码劣化的方式有很多，与当初是谁写的毫无关系。他的工作定义是：遗留代码就是没有测试的代码，无论其年代、语言或外观如何。<sup>[1](https://ptgmedia.pearsoncmg.com/images/9780131177055/samplepages/0131177052.pdf)</sup>

其理由出于实用而非审美。有了测试，团队就能快速且可验证地改变行为；没有测试，谁也不知道代码是在变好还是变坏。费瑟斯把对未经测试的代码做大改动比作在没有安全网的情况下做空中体操，并指出，即便是格外整洁的代码库，其改动速度也慢于测试完备的代码库。<sup>[1](https://ptgmedia.pearsoncmg.com/images/9780131177055/samplepages/0131177052.pdf)</sup> 他说过，这个定义源自一次咨询会议上的挫败感，是一个带有目的的定义，意在把人引向解决方案，而其他定义也同样有用。在后来的访谈中，他把“遗留”描述为一种基于代码有多难理解的主观判断，并认可这样一种说法：当团队更替快于代码更替时，产生出来的就是遗留代码。<sup>[4](https://techleadjournal.dev/episodes/195/)</sup><sup> • </sup><sup>[8](https://gotopia.tech/episodes/228/working-effectively-with-legacy-code)</sup><sup> • </sup><sup>[9](https://www.software-engineering-unlocked.com/legacy-code-michael-feathers/)</sup>

## 安全地处理遗留代码

**依赖陷阱。** 要安全地修改代码，你需要测试；但为未经测试的代码编写测试，通常又需要先修改它。费瑟斯点明了这一陷阱，并围绕“以小步幅脱身”构建了他的方法。<sup>[10](https://techdebt.now/techniques/test-characterization/)</sup> 他的总体策略是：找出变更点，找到一个拐点，通过打破外部与内部依赖、编写测试来覆盖该点，实施变更，然后重构已被覆盖的代码。<sup>[11](https://objectmentor.com/resources/articles/WorkingEffectivelyWithLegacyCode.pdf)</sup>

**接缝。** 接缝是程序中的一个位置，可以在不修改该处代码的情况下改变其行为。费瑟斯区分了三种：预处理接缝，在带 [C 预处理器](https://www.edgepedia.org/zh/c-preprocessor)的语言中使用 `#define` 宏；链接接缝，在构建或加载时替换为另一个库或目标文件，例如通过 `LD_LIBRARY_PATH` 或 `CLASSPATH`；以及多态接缝，利用依赖注入，使程序或测试能在运行时选择具体实现。多态接缝最为灵活，通常是首选；而任何一种接缝能否用好，都取决于定义它的接口质量。<sup>[3](https://mike-bland.com/2023/08/23/legacy-code-seams-and-the-most-important-design-guideline.html)</sup>

**特征测试。** [特征测试](https://www.edgepedia.org/zh/characterization-test)记录某段软件的当前行为，并在代码变动过程中将其保留下来。开发者用选定的输入调用代码，观察实际输出，并把该输出记录为期望值，于是测试锁定的是系统现在的所作所为，而不是任何人认为它应该做什么。费瑟斯指出，这类测试是对“实际是什么”的定义，而不是对“正确是什么”的定义；令人意外的结果正是关于系统的信息。这种技术也被称为钉住测试或黄金主本测试。<sup>[4](https://techleadjournal.dev/episodes/195/)</sup><sup> • </sup><sup>[12](https://code.furybee.org/articles/legacy-code-characterization-tests-seams/)</sup> 哪怕只有一个特征测试，也能提供一个安全的立足点，让人可以着手工作；而测试覆盖最好集中在即将改动的区域，因为覆盖整个遗留系统耗时甚久。<sup>[13](https://booksforagents.com/books/working-effectively-with-legacy-code)</sup><sup> • </sup><sup>[14](https://noelrappin.com/audio/tdr-011/transcript/)</sup>

## 系统层面的现代化

当工作单位是整个系统而不是某个类时，主流的渐进式策略是[绞杀榕模式](https://www.edgepedia.org/zh/strangler-fig-pattern)，由软件作家兼顾问[马丁·福勒](https://www.edgepedia.org/zh/martin-fowler-software-engineer)提出，其类比是那种绕着宿主树生长、直至宿主被取代的榕藤。新功能在遗留系统之外构建，流量被逐步导向新组件，直到旧系统可以退役。福勒最初的博文题为“绞杀者应用”（Strangler Application）；他后来改题为“绞杀榕应用”（Strangler Fig Application），以让这个植物学隐喻保持可见。<sup>[5](https://martinfowler.com/bliki/StranglerFigApplication.html)</sup>

这一做法需要过渡期架构，让新系统与遗留系统共存——这些代码在现代化完成后将被丢弃；福勒认为，风险降低与价值提前兑现足以抵过这笔成本。它还需要组织层面的变革，因为遗留系统之所以僵化，部分原因正是造就它们的那些流程。<sup>[5](https://martinfowler.com/bliki/StranglerFigApplication.html)</sup> AWS 针对该模式给出的指南指出两项前提：一是能够访问单体应用的代码库，因为调用必须被拦截并经防腐层路由；二是领域足够清晰，因为过早拆分、服务边界划错，代价高昂。<sup>[15](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/strangler-fig.html)</sup>

## 成本与当前实践

遗留系统带来可度量的成本。由萨万塔（Savanta）为[派加系统](https://www.edgepedia.org/zh/pegasystems)（Pegasystems）开展的一项研究报告称，企业每年因过时技术损失约 3.7 亿美元，其中遗留系统改造项目约占 1.34 亿美元，失败项目平均每年约 5800 万美元，维护约 5600 万美元。<sup>[6](https://www.itpro.com/business/digital-transformation/it-leaders-are-throwing-money-away-with-legacy-systems-enterprises-report-usd370-million-in-losses-each-year-due-to-outdated-tech)</sup> 毕马威（KPMG）2025 年的一项调查发现，约 55% 的团队将 20%–40% 的工程产能用于技术债务；52% 的受访者正在实施或试点 AI 辅助的代码重构或遗留代码分析以减少债务，AI 辅助测试的比例与之相同；该调查将这类用途概括为生产力上的收益，而架构层面的现代化寥寥。<sup>[7](https://kpmg.com/kpmg-us/content/dam/kpmg/pdf/2025/technology-sector-ma-survey.pdf)</sup>

费瑟斯的方法也被应用于更新的问题。评论 AI 生成代码的人建议采用与处理遗留系统相同的顺序：先补充足够的测试，以便对监督有把握，然后再改动代码——因为 AI 生成的代码可能陷入这样一种状态：每一次尝试修复都会弄坏别的地方。<sup>[16](https://www.techradar.com/pro/whatever-you-try-to-fix-breaks-things-even-more-how-to-avoid-the-hidden-dangers-of-ai-code)</sup>

## References

1. [Working Effectively with Legacy Code, sample preface, Michael C. Feathers, Pearson](https://ptgmedia.pearsoncmg.com/images/9780131177055/samplepages/0131177052.pdf)
2. [Working Effectively with Legacy Code, 1st edition, Pearson](https://www.pearson.com/en-us/subject-catalog/p/working-effectively-with-legacy-code/P200000008984)
3. [Legacy code, seams, and the most important design guideline, Mike Bland](https://mike-bland.com/2023/08/23/legacy-code-seams-and-the-most-important-design-guideline.html)
4. [Working Effectively with Legacy Code and AI Coding Assistants, Tech Lead Journal episode 195](https://techleadjournal.dev/episodes/195/)
5. [Strangler Fig Application, Martin Fowler](https://martinfowler.com/bliki/StranglerFigApplication.html)
6. [IT leaders are throwing money away with legacy systems, ITPro](https://www.itpro.com/business/digital-transformation/it-leaders-are-throwing-money-away-with-legacy-systems-enterprises-report-usd370-million-in-losses-each-year-due-to-outdated-tech)
7. [KPMG Technology Sector M&A Survey 2025](https://kpmg.com/kpmg-us/content/dam/kpmg/pdf/2025/technology-sector-ma-survey.pdf)
8. [Working Effectively with Legacy Code, Gotopia Bookclub episode 228](https://gotopia.tech/episodes/228/working-effectively-with-legacy-code)
9. [How to work with legacy code with Michael Feathers, Software Engineering Unlocked](https://www.software-engineering-unlocked.com/legacy-code-michael-feathers/)
10. [Characterization Tests for Legacy Code, TechDebt.now](https://techdebt.now/techniques/test-characterization/)
11. [Working Effectively with Legacy Code article PDF, Michael Feathers, Object Mentor](https://objectmentor.com/resources/articles/WorkingEffectivelyWithLegacyCode.pdf)
12. [Refactoring Legacy Code Safely: Characterization Tests and Seams, FuryBee](https://code.furybee.org/articles/legacy-code-characterization-tests-seams/)
13. [Working Effectively with Legacy Code, Books for Agents](https://booksforagents.com/books/working-effectively-with-legacy-code)
14. [Transcript: Avoiding Legacy Code with Michael Feathers, Noel Rappin](https://noelrappin.com/audio/tdr-011/transcript/)
15. [Strangler fig pattern, AWS Prescriptive Guidance](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/strangler-fig.html)
16. [How to avoid the hidden dangers of AI code, TechRadar](https://www.techradar.com/pro/whatever-you-try-to-fix-breaks-things-even-more-how-to-avoid-the-hidden-dangers-of-ai-code)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software testing and quality › Testing techniques and levels

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/legacy-code

English original: https://www.edgepedia.org/legacy-code
