# 代码重构

代码重构是指在不改变软件外部行为的前提下，对现有源代码进行重新组织、调整其内部结构的过程，目的是使代码更易于理解、修改成本更低。其核心是一系列小型的、保持行为不变的变换，每一次变换单独来看都小得似乎不值得去做，但其累积效应却能显著改善设计。<sup>[1](https://refactoring.com/)</sup>

| 关键事实 | 详情 |
|---|---|
| 定义 | 对现有代码体进行重新组织，在不改变其外部行为的情况下调整内部结构；本质是一系列小型的保持行为不变的变换<sup>[1](https://refactoring.com/)</sup> |
| 学术起源 | 威廉·F·奥普代克（William F. Opdyke）1992年在伊利诺伊大学厄巴纳-香槟分校的博士论文《重构面向对象框架》（*Refactoring Object-Oriented Frameworks*），定义了一组支持面向对象框架的设计、演化和复用的程序重组操作<sup>[2](https://www.ideals.illinois.edu/items/72240)</sup> |
| 经典著作 | 马丁·福勒（Martin Fowler）的《重构：改善既有代码的设计》（*Refactoring: Improving the Design of Existing Code*），第一版1999年，第二版2018年，描述了约七十种重构手法，每种均附有动机、做法和示例<sup>[3](https://martinfowler.com/books/refactoring.html)</sup> |
| 实践与理论的差异 | 在微软对328名工程师的一项调查中，78%的人将重构定义为改善程序行为某一方面的变换，46%的人完全未提及行为保持<sup>[4](https://kelloggm.github.io/martinjkellogg.com/teaching/cs490-sp23/assets/refactoring.pdf)</sup> |
| 工具支持 | 集成开发环境（IDE）可自动化常见操作，如提取方法、重命名、内联、更改签名和安全删除<sup>[5](https://www.jetbrains.com/help/idea/refactoring-source-code.html?keymap=gnome)</sup> |
| 长期效果 | 一项对超过85万个重构实例的研究发现，中等持续时长的重构（其影响持续9至19次后续变更）在可持续性与成本效益之间取得了最佳平衡，而影响持续超过19次后续操作的重构则更容易引入缺陷<sup>[6](https://link.springer.com/article/10.1007/s10664-025-10801-3)</sup> |
| AI辅助 | 在一项200个案例的研究中，ChatGPT生成的重构代码有88%的案例可以编译，但仅29%的案例正确执行了预期的重构，而NetBeans IDE的正确率为67%<sup>[7](https://ietresearch.onlinelibrary.wiley.com/doi/abs/10.1049/sfw2/3348017)</sup> |

## 定义与目的

马丁·福勒是一位英国软件工程师和作家，以其关于软件架构和敏捷开发的写作而闻名，他将重构定义为一种有控制地改善现有代码库设计的技术。其目的是使软件更易于理解、修改成本更低；为其他目的（如修复缺陷或添加功能）而做的相同结构改动，在此意义上不算重构。<sup>[1](https://refactoring.com/)</sup><sup> • </sup><sup>[8](https://martinfowler.com/bliki/RefactoringBoundary.html)</sup>

该方法基于两条原则：小步前进，频繁测试。<sup>[9](https://martinfowler.com/distributedComputing/refactoring.pdf)</sup>每一次变换都足够小，以至于错误很容易被发现；又因为系统从不处于损坏状态，代码库可以在较长时期内逐步重构。<sup>[3](https://martinfowler.com/books/refactoring.html)</sup>福勒的书对每一种变换（称为重构手法）进行了编目，并将其与代码库中提示应在何处应用的“代码坏味道”配对说明。<sup>[3](https://martinfowler.com/books/refactoring.html)</sup>

## 历史

学术基础来自威廉·F·奥普代克，他是一位美国计算机科学家，当时在伊利诺伊大学厄巴纳-香槟分校，1992年在拉尔夫·约翰逊（Ralph Johnson）指导下完成的博士论文定义了一组支持面向对象应用框架的设计、演化和复用的程序重组操作。<sup>[2](https://www.ideals.illinois.edu/items/72240)</sup>奥普代克将每种重构结构化为前置条件加变换的形式，这一方法后来被应用于其他语言；拉尔夫·格里斯沃尔德（Ralph Griswold）早期关于程序重组的工作，以及约翰·布兰特（John Brant）和唐·罗伯茨（Don Roberts）为Smalltalk开发的Refactoring Browser，是同一时期的并行贡献。<sup>[9](https://martinfowler.com/distributedComputing/refactoring.pdf)</sup><sup> • </sup><sup>[10](https://citeseerx.ist.psu.edu/document?doi=e699e811918881f2af1b457b3453782e290c7ae2&repid=rep1&type=pdf)</sup>

福勒的书于1999年首次出版（[肯特·贝克](https://www.edgepedia.org/zh/kent-beck)（Kent Beck）是贡献者之一），2018年修订，将这一实践带入主流开发。如今已有若干开发环境能够自动化书中描述的许多重构手法，重构已成为软件开发术语中一个成熟完整的组成部分。<sup>[3](https://martinfowler.com/books/refactoring.html)</sup>2020年的一项系统性文献综述分析了三十年间3183篇关于重构的研究论文，反映出该领域已从代码级重组扩展到架构、模型和需求层面。<sup>[11](https://arxiv.org/abs/2007.02194)</sup>

## 两顶帽子

福勒的“两顶帽子”比喻将重构与所有其他类型的代码修改区分开来。重构时，每一次修改都是小型的、保持行为不变的，开发者只在测试全部通过的状态下工作；任何测试失败都意味着出了错。添加功能时，开发者添加新测试，可能使现有测试失败，且不受保持行为不变的编辑的约束。程序员可能每隔几分钟就在两顶帽子之间切换，但一次只能戴一顶帽子，将两种活动分开有助于保持工作专注。<sup>[12](https://martinfowler.com/articles/workflowsOfRefactoring/fallback.html)</sup>

自动化测试是这一切安全进行的保障。维护良好的单元测试，按定义就是实际行为的最新表示，对于将无畏重构变成日常习惯至关重要。<sup>[13](https://martinfowler.com/articles/testing-culture.html)</sup>

## 工具支持

现代IDE可自动化最常见的操作。[IntelliJ IDEA](https://www.edgepedia.org/zh/intellij-idea)列出的最受欢迎的重构包括提取方法、提取常量、提取字段、提取参数、引入变量、重命名、内联、更改签名、复制/移动和安全删除；安全删除在移除文件或符号前会检查其使用情况，提取方法则将选中的代码片段移入一个新方法并用调用替换之。<sup>[5](https://www.jetbrains.com/help/idea/refactoring-source-code.html?keymap=gnome)</sup><sup> • </sup><sup>[14](https://www.jetbrains.com/help/idea/extract-method.html)</sup>[Visual Studio](https://www.edgepedia.org/zh/visual-studio)为C#、Visual Basic和C++提供了等效的快速操作，包括提取和内联重构、重命名和移动操作以及签名更改。<sup>[15](https://learn.microsoft.com/visualstudio/ide/refactoring-in-visual-studio)</sup>

在大规模应用方面，谷歌开发了Refaster，该工具用普通的、可编译的前后代码示例来指定Java重构，而无需专门的语言；Java核心库团队使用它在谷歌的Java代码库中执行了各种各样的重构。<sup>[16](https://research.google/pubs/scalable-example-based-refactorings-with-refaster/)</sup>

## 行为保持

行为保持是重构的定义性约束，而保证行为保持是一个活跃的研究问题。文献中研究的方法包括形式验证、语言变换、动态分析、基于前置条件和后置条件的规约、不变式以及自动化测试；一项系统性映射研究发现，某些重构操作在行为保持方面仍缺乏充分研究，而组合多种策略能更好地检测对程序语义的违反。<sup>[17](https://arxiv.org/abs/2106.13900)</sup>尽管有可用的工具，调查发现开发者往往更倾向于手动重构，理由是缺乏对自动化重构的信任以及对破坏代码语义的担忧。<sup>[17](https://arxiv.org/abs/2106.13900)</sup>

## 实践中的重构

实地研究表明，实践与教科书定义存在分歧。在微软的研究中，对328名工程师的问卷调查、半结构化访谈以及对[Windows 7](https://www.edgepedia.org/zh/windows-7)版本历史的定量分析发现，开发者并不将重构局限于保持语义的变换：78%的人将其定义为改善程序行为某一方面的变换，如可读性、可维护性或性能；71%的人表示，编目的基本重构手法通常是更大规模、更高层次工作的一部分。<sup>[4](https://kelloggm.github.io/martinjkellogg.com/teaching/cs490-sp23/assets/refactoring.pdf)</sup>定量分析发现，优先重构的前5%模块在模块间依赖性和若干复杂度指标上的降低幅度高于后95%的模块，但规模增长也更多，这表明重构的影响需要多维度评估。<sup>[18](https://www.microsoft.com/en-us/research/publication/an-empirical-study-of-refactoring-challenges-and-benefits-at-microsoft/)</sup>

重构也很少是一项独立的活动。一项对商业C#软件的研究发现，重构往往与其他修改同时发生，而非作为独立的维护工作，且在提交注释中很少被提及；同一研究指出了固有风险：重构期间引入的缺陷会导致受影响类中进一步的修改和修复。<sup>[19](https://www.sciencedirect.com/science/article/pii/S0167642314005711)</sup>[代码审查](https://www.edgepedia.org/zh/code-review)流程也塑造着实践：谷歌的审查标准指示审查者在变更确实改善了系统整体代码健康时即予批准，即使它并不完美，以免可维护性改进被拖延数天或数周。<sup>[20](https://google.github.io/eng-practices/review/reviewer/standard.html)</sup>

投入的动机是可量化的。谷歌一项针对1200多个C++和Java项目的大规模研究发现，系统架构越复杂（以传播成本和结构性反模式衡量），用于修复缺陷而非添加功能的代码行就越多，这为团队论证重构的必要性提供了客观依据。<sup>[21](https://research.google/pubs/understanding-architectural-complexity-maintenance-burden-and-developer-sentiment-a-large-scale-study/)</sup>

## 长期效果

重构的收益在不同操作之间并不均匀。一项对Apache项目中98种重构类型、20个族系、超过85万个重构实例的大规模研究发现，大多数重构具有短至中等寿命的涟漪效应：结构性重构的影响持续时间更长但风险更高，而局部化变更消退更快但更稳定。影响持续9至19次后续变更的重构表现出最低的变更倾向性，处于持久性与成本之间的最佳平衡点；而影响持续超过19次后续操作的重构则更容易引入缺陷，尤其是在“尝试”“断言”和“参数化”等族系中。<sup>[6](https://link.springer.com/article/10.1007/s10664-025-10801-3)</sup>

## AI辅助重构

大语言模型增加了一条新的自动化路径，但结果喜忧参半。在一项使用五个Java开源应用的200个测试用例的实证研究中，ChatGPT生成的重构代码有88%的案例可以编译，但仅29%的案例正确执行了预期的重构，而NetBeans IDE的正确率为67%；作者得出结论，此类工具尚未准备好用于大规模应用的完全自动化重构，仍需要人工监督。<sup>[7](https://ietresearch.onlinelibrary.wiley.com/doi/abs/10.1049/sfw2/3348017)</sup>2025年IEEE/ACM IDE研讨会的一篇立场论文同样发现，大语言模型的易错性和产生幻觉的可能性限制了其集成到IDE等自动化重构流水线中，通常需要人工参与来验证修改。<sup>[22](https://ieeexplore.ieee.org/abstract/document/11052685)</sup>

[OpenAI Codex](https://www.edgepedia.org/zh/openai-codex-coding-agent)、Claude Code和Cursor等智能体编程工具则更加自主。一项对开源Java项目中12256个拉取请求中的15451个重构实例的研究发现，智能体在26.1%的提交中明确以重构为目标，但其工作以低层次的、面向一致性的编辑为主，如更改变量类型（11.8%）、重命名参数（10.4%）和重命名变量（8.5%），反映出它们偏好局部化改进，而非人类重构中常见的高层次设计变更。<sup>[23](https://arxiv.org/abs/2511.04824)</sup>

## References

1. [Refactoring, Martin Fowler](https://refactoring.com/)
2. [Opdyke, William F. (1992). Refactoring Object-Oriented Frameworks. PhD thesis, University of Illinois at Urbana-Champaign, IDEALS](https://www.ideals.illinois.edu/items/72240)
3. [Refactoring: Improving the Design of Existing Code, Martin Fowler](https://martinfowler.com/books/refactoring.html)
4. [A field study of refactoring challenges and benefits (Kim et al., IEEE Transactions on Software Engineering)](https://kelloggm.github.io/martinjkellogg.com/teaching/cs490-sp23/assets/refactoring.pdf)
5. [Code refactoring, IntelliJ IDEA Documentation](https://www.jetbrains.com/help/idea/refactoring-source-code.html?keymap=gnome)
6. [Analyzing the ripple effects of refactoring, Empirical Software Engineering (Springer)](https://link.springer.com/article/10.1007/s10664-025-10801-3)
7. [Refactoring Object-Oriented Software With ChatGPT: An Empirical Study, IET Software](https://ietresearch.onlinelibrary.wiley.com/doi/abs/10.1049/sfw2/3348017)
8. [Refactoring Boundary, Martin Fowler](https://martinfowler.com/bliki/RefactoringBoundary.html)
9. [Refactoring, Distributed Computing column (Fowler)](https://martinfowler.com/distributedComputing/refactoring.pdf)
10. [Refactoring Aspect-Oriented Software](https://citeseerx.ist.psu.edu/document?doi=e699e811918881f2af1b457b3453782e290c7ae2&repid=rep1&type=pdf)
11. [30 Years of Software Refactoring Research: A Systematic Literature Review, arXiv](https://arxiv.org/abs/2007.02194)
12. [Workflows of Refactoring, Martin Fowler](https://martinfowler.com/articles/workflowsOfRefactoring/fallback.html)
13. [Goto Fail, Heartbleed, and Unit Testing Culture, Martin Fowler](https://martinfowler.com/articles/testing-culture.html)
14. [Extract method, IntelliJ IDEA Documentation](https://www.jetbrains.com/help/idea/extract-method.html)
15. [Refactor code, Visual Studio (Windows), Microsoft Learn](https://learn.microsoft.com/visualstudio/ide/refactoring-in-visual-studio)
16. [Scalable, Example-Based Refactorings with Refaster, Google Research](https://research.google/pubs/scalable-example-based-refactorings-with-refaster/)
17. [On Preserving the Behavior in Software Refactoring: A Systematic Mapping Study, arXiv](https://arxiv.org/abs/2106.13900)
18. [An Empirical Study of Refactoring Challenges and Benefits at Microsoft, Microsoft Research](https://www.microsoft.com/en-us/research/publication/an-empirical-study-of-refactoring-challenges-and-benefits-at-microsoft/)
19. [The effect of refactoring on change and fault-proneness in commercial C# software, ScienceDirect](https://www.sciencedirect.com/science/article/pii/S0167642314005711)
20. [The Standard of Code Review, Google eng-practices](https://google.github.io/eng-practices/review/reviewer/standard.html)
21. [Understanding Architectural Complexity, Maintenance Burden, and Developer Sentiment, Google Research](https://research.google/pubs/understanding-architectural-complexity-maintenance-burden-and-developer-sentiment-a-large-scale-study/)
22. [LLM-Driven Code Refactoring: Opportunities and Limitations, IEEE Xplore](https://ieeexplore.ieee.org/abstract/document/11052685)
23. [Agentic Refactoring: An Empirical Study of AI Coding Agents, arXiv](https://arxiv.org/abs/2511.04824)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

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

Copyright 2026 Edgepedia

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

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

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