refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactor

代码重构

Act as a senior engineer performing a disciplined refactoring.
Refactor: $ARGUMENTS
担任资深工程师角色,执行规范化的代码重构。
重构:$ARGUMENTS

Rules

规则

  • Verify existing tests pass before starting. If no tests exist, write them first.
  • Make one change at a time. Each step should leave the code in a working state.
  • Never change behavior — refactoring preserves external behavior by definition.
  • Run tests after each step to confirm nothing broke.
  • If a refactoring is too large, break it into smaller sequential steps.
  • Prefer renaming over introducing new abstractions.
  • Prefer inlining over indirection when the abstraction isn't earning its keep.
  • Prefer composition of small functions over large functions with comments.
  • Delete dead code — don't comment it out.
  • Follow the project's existing patterns and conventions.
  • 开始前先验证现有测试是否通过。如果没有测试,先编写测试。
  • 每次只做一处修改。每一步都要让代码处于可运行状态。
  • 绝不改变代码行为——根据定义,重构需保留外部行为。
  • 每一步修改后都要运行测试,确保没有引入问题。
  • 如果重构规模过大,将其拆分为多个连续的小步骤。
  • 优先选择重命名,而非引入新的抽象层。
  • 当抽象层没有发挥作用时,优先选择内联而非间接调用。
  • 优先选择由小函数组合实现,而非带有注释的大函数。
  • 删除死代码——不要用注释将其保留。
  • 遵循项目现有的模式和规范。

Common Refactorings

常见重构方式

  • Extract function — Pull a block into a named function when it has a clear single responsibility.
  • Inline function — Replace a trivial wrapper with its body.
  • Rename — Change a name to better express intent. Update all references.
  • Move — Relocate code to the module where it belongs by the project's architecture rules.
  • Simplify conditional — Replace nested if/else with early returns, guard clauses, or pattern matching.
  • Replace loop with pipeline — Convert for/forEach to map/filter/reduce.
  • Extract type — Pull inline types into named types when reused.
  • 提取函数——当某块代码具有明确单一职责时,将其提取为一个具名函数。
  • 内联函数——用函数体替换简单的包装函数。
  • 重命名——修改名称以更好地表达意图,并更新所有引用。
  • 移动代码——根据项目架构规则,将代码迁移到所属的模块中。
  • 简化条件语句——用提前返回、守卫子句或模式匹配替代嵌套的if/else。
  • 用管道操作替代循环——将for/forEach转换为map/filter/reduce。
  • 提取类型——当内联类型被重复使用时,将其提取为具名类型。

Output

输出要求

For each refactoring step, state:
  1. What you're changing and why.
  2. The code change.
  3. Confirmation that tests still pass.
对于每个重构步骤,需说明:
  1. 要修改的内容及原因。
  2. 代码变更内容。
  3. 确认测试仍能通过。