> For the complete documentation index, see [llms.txt](https://joyous-x.gitbook.io/mbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joyous-x.gitbook.io/mbook/part-skill/catalog-1/note_of_refactor.md).

# 代码重构培训(笔记)

* 持续集成：保证日常流程中所有开发人员的code clean
* 对于眼中的烂项目，如果用同样的思路去重构，只不过是一个新的烂项目的开始
* 生成烂代码的原因，一般人都会认为有以下几种甚至更过：
  * 需求变更
  * 旧的逻辑难以维护
  * 交付压力
  * 自己的代码设计(这个是关键)
* 烂代码产生的一个重要原因是：
  * 破窗效应 ---> 惯性 ---> 好的更好，坏的更坏
* 死循环：无单元测试 ---> 不敢动以前代码 ---> 烂代码
  * 单元测试：保证功能细节正确
  * 测试人员：集成测试，保证产品功能正常
* 重构 不等于 重写
  * 重构是，小步迭代，逐步验证。重写是，完全推翻重来。
* 重构的重要原则：
  * 重构是在不改变原有代码行为的前提下，对其进行的一系列小步骤的改进。
  * 重构是baby step，也就是小步测试，逐步完成。
* first， do no harm。重构过程，首先要做到不伤害。
* 重构时：
  * 重要的就是要解耦（函数内、函数间等），否则很难重构。
  * 重构时，勿以善小而不为，勿以恶小而为之&#x20;
* 重构中，要充分使用工具：
  * 编程工具中 refactor 功能的使用
  * svn status
  * 持续集成，code review（代码质量的可视化）
* 在原有代码基础上改动时，代码质量保证方法：
  * 不伤害
    * 隔离原有代码，尽量不该动原有逻辑，先保证原有代码不动，再增加新功能
    * 优先重构痛点：经常改动的复杂代码
  * 逐步验证
    * 单元测试
  * 过渡设计
* 代码是债务：
  * 代码clean，需要从刻意到随意
* 把数据处理封装，避免需要修改时，到处找数据的使用点进行修改，而造成 漏掉 或者 修改点过多造成工作量过大的问题。
* public函数是流程函数，只应由各种独立功能的函数组成
* 修改代码时，如果没有做到新旧代码隔离，代码会逐步变成各种补丁交叉，造成可读性、可维护性急剧下降
* 写新代码时要做到：
  * 小步重构
    * 一定要用单元测试保证
    * 制定代码底限或者重构底限，依照规则review代码（用规则发现代码中坏味道）
  * code review
    * 保证 code clean，延长代码的生命周期
* 代码隔离的四大类方法：
  * 新生方法 sprout method
  * 新生类 sprout class
    * 接口、观察者、直接加功能类
  * 外覆方法 wrapper method
  * 外覆类 wrapper class
    * 代理、装饰、aop方式
* 单一原则
  * 单一抽象原则（SLAP），单一代码层次抽象
  * 单一原则，查询、执行分离

> 重构相关书籍： 《重构-改善既有代码的设计》 《程序员的职业素养》 《修改代码的艺术》


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://joyous-x.gitbook.io/mbook/part-skill/catalog-1/note_of_refactor.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
