# 任务5：消除魔法字符串

魔法字符串（即：在业务逻辑代码中直接使用的字符串字面量）是一种常见的坏味道。避免使用字面量，首先是为了**消除重复**——如果一个字面量在多个地方出现，一旦需要修改，就得找到所有使用的地方逐一修改，这会增加维护的工作量和出错的可能性；其次，是为了**更好地表义**——如果程序里多次出现`2.72`这个字面量，未必所有读者都能立即反应出这个数字是什么，但如果出现的是`e`这个变量，读者可能会更快地理解到，它代表的是自然对数的底数。

在镶金玫瑰这个例子中，我们确实看见了不少值得消除的魔法字符串，其中许多还是重复的，比如下面这个片段：

```javascript
  ...
  if (
    item.name !== "Aged Brie" &&
    item.name !== "Backstage passes to a TAFKAL80ETC concert"
  ) {
    if (item.quality > 0) { ... }
  } else {
    if (item.quality < 50) {
      item.quality = item.quality + 1;
      if (item.name === "Backstage passes to a TAFKAL80ETC concert") { ... }
    }
  }
  ...
```

## 你的任务

Java：

```
git checkout task-5-magic-strings
./gradlew clean build
```

JavaScript：

```
git checkout task-5-magic-strings
npm test
```

1. 消除多处重复的魔法字符串字面量（包含测试文件中的重复）
2. 要求小步前进，每一步修改之后马上运行所有测试，确保软件行为不变

## 思考

* 你有哪些消除重复的字符串字面量的办法？
* 在这个重构中，你采用的是什么方法？


---

# 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/7-task-5.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.
