> For the complete documentation index, see [llms.txt](https://ethan-lin.gitbook.io/refactoring/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ethan-lin.gitbook.io/refactoring/dan-wei-zhuan-huan/9-extract-calculation-function.md).

# 任务6：提炼计算函数

好，走到这里，我们已经离一开始前进了许多：奇怪的命名不见了，魔法字符串已经被更表意的枚举类型`Unit`替代，表示英寸的`f`也被很轻松地改成了`Unit.FOOT`，收获不小！

接下来的任务，是消除一个不太明显的味道，也就是在`as()`方法中重复的`new Length`创建逻辑。仔细观察，其实`Length`对象的创建过程，唯一区别是在计算不同的`value`值。不过，要消除重复的对象创建代码，我们还得做点准备工作，那就是把这部分关于`value`的计算逻辑先剥离出来。

![](/files/-Lr9XDRLzUiQlC5pzeoo)

## 你的任务

Java：

```
git checkout task-6
./gradlew test
```

JavaScript：

```
git checkout task-6
npm test
```

1. 动手之前，先花几分钟思考一下重构步骤：如何做到平滑替换？
2. 严格按照重构步骤执行重构，频繁运行测试
3. `git checkout final`看一下参考步骤，找出与你设定步骤的异同
4. 多练几遍

## 参考资料

* 《重构 2》6.1 提炼函数（Extract Function）
* 《重构 2》10.3 以卫语句取代嵌套条件表达式（Replace Nested Conditional with Guard Clauses）


---

# 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://ethan-lin.gitbook.io/refactoring/dan-wei-zhuan-huan/9-extract-calculation-function.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.
