> For the complete documentation index, see [llms.txt](https://zhouhao4221.gitbook.io/haiqing-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/refactoring.md).

# 代码重构

代码能跑，但结构需要改善时使用。目标是在不改变外部行为的前提下提升可读性、减少耦合、让 AI 后续操作更容易。

***

## 什么时候用

以下情况考虑重构：

* 函数超过 50 行，做了不止一件事
* 下次修改这块代码时，AI 需要理解太多隐式上下文
* 想对某个模块加功能，但现有结构让改动变得危险

不适合的场景：代码逻辑本身有错，那是 bug 修复，不是重构。

## 准备什么

* **目标代码**：要重构的函数或模块全文，不是片段
* **重构目标**：具体说明想改善什么。"更好"不够具体，要说"拆分成两个职责单一的函数"或"消除对全局变量 X 的依赖"
* **不能改动的部分**：对外接口签名、已有测试依赖的行为、被其他模块直接调用的函数名

"不能改动的部分"最容易被忽略。没有明确说明时，AI 可能改了调用方依赖的接口，导致其他地方编译失败。

## 怎么触发

**单次任务**

```
先读 04-prompt/code/refactoring.md，
目标代码在 [文件路径]，
重构目标：[具体说明]，
不能改动：[列出接口名、函数名]。
请进行重构。
```

**写入 CLAUDE.md**

```markdown
## 重构
重构代码时：
1. 要求输出重构后的完整代码，不是 diff
2. 要求列出每项改动和改动原因
3. 要求标出哪些行为变化需要人工核查
```

## 好的输出是什么样的

* 输出完整代码，不是只给出差异部分（diff 在真实项目里很难直接应用）
* 每项改动有对应的一句话说明：改了什么、为什么这样改
* 明确标出有哪些行为变化需要人工核查（即使是"无行为变化"也要明确说）
* 不引入新的运行时依赖

## 常见失败模式

* **改了不该改的接口**：没有明确说明不能改动的部分。重构前先列清楚哪些是外部依赖
* **大泥球代码无从下手**：一个函数混合了三层职责，AI 的拆分方向是错的。这种情况先人工确定边界，再让 AI 执行
* **只给 diff**：AI 默认给差异描述，修改代码时难以直接用。明确要求"输出完整代码"
* **行为悄悄变了**：重构后某个边界条件的处理方式改变了，但没有提示。要求 AI 列出所有潜在行为变化

***

## 版本历史

* v1.0：初始版本


---

# 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://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/refactoring.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.
