# 任务4：重组逻辑

上一步中，我们对代码做了一些简单的清理，修复了一些 IDE 和 lint 工具提示的问题，还把一个老旧的`for (i = 0; i < items.length; i++)`循环替代成了更加声明式的`for (item of items)`循环。

做完简单的清理，将循环元素从`this.items[i]`替换成`item`以后，我们突然看见了一个更明显的坏味道：屏幕上出现了满篇对`item`变量的查询和更新：`item.quantity = ...`、`item.sell_in = ...`。这不正是“依恋情结”（Feature Envy）的坏味道吗？翻开《重构 2》的第 3.9 节，你就发现这段话彷如就在描写当下的情景：“……有时你会发现，一个函数跟另一个模块中的函数或者数据交流格外频繁，远胜于自己所处模块内部的交流。”

那么，最自然的想法，自然是先把对`item`的更新行为挪到`Item`类中去。

## 你的任务

Java：

```
git checkout task-4-feature-envy
./gradlew clean build
```

JavaScript：

```
git checkout task-4-feature-envy
npm test
```

1. 重构代码，消除“依恋情结”的坏味道
2. 要求小步前进，每一步修改之后马上运行所有测试，确保软件行为不变

## 反思

* 搬移过程是否顺畅？有没有纠结的地方？
* 有没有一次尝试迈太大的步子？
* 如果再来一次，如何可以缩小重构-运行测试的步伐？

## 参考

* 《重构 2》3.9 依恋情结（Feature Envy）
* 《重构 2》第 3 章：代码的坏味道


---

# Agent Instructions: 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:

```
GET https://ethan-lin.gitbook.io/refactoring/xiang-jin-mei-gui/6-task-4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
