AGENT SKILL

refactor

Use when refactoring existing code to improve readability or maintainability while preserving behavior.

License 许可
MIT
最近更新
2026-10-29
Stars
★ 0
Forks
0

01 前言 Front Matter

name
refactor
license
MIT
description
Use when refactoring existing code to improve readability or maintainability while preserving behavior.

03 SKILL.md 正文

Refactor

Improve existing code structure without changing its observable behavior. Prefer the smallest change that addresses a clear maintenance problem.

When to Use

  • Code is difficult to understand or safely change.
  • A function or module has multiple responsibilities.
  • Logic is duplicated, deeply nested, or coupled to the wrong object.
  • A requested feature is difficult because of the current structure.
  • The user asks to clean up or refactor existing code.

Refactoring Workflow

  1. Understand the behavior. Read the target code and its callers. Check relevant tests, types, exports, fixtures, and configuration. Identify the behavior and the specific maintenance problem.
  2. Choose one change. Make the smallest change that addresses that problem. Follow the codebase's conventions and reuse its existing helpers and patterns.
  3. Verify. Run relevant tests when verification is requested or repository instructions require them. If a non-trivial refactor lacks coverage, report that gap; add characterization tests when requested or required. If checks cannot run, say what remains unverified.
  4. Review the result. Inspect the diff for changes to return values, errors, ordering, side effects, public interfaces, and persisted or serialized data.
  5. Finish cleanly. Remove code only when it is confirmed unused. Update comments or docs only when the refactor makes them inaccurate.

Keep the work in a recoverable version-control state and follow the repository's workflow. A separate branch or commit is useful when the project expects one; it is not a requirement for every refactor.

Core Rules

  • Preserve behavior. Do not change outputs, errors, side effects, ordering, or public contracts as part of a refactor. Treat bug fixes and feature changes as separate work.
  • Work in small steps. Make one focused change at a time.
  • Keep it simple. Prefer the least new code that solves the identified problem. Add an abstraction or design pattern only when it makes the current code easier to understand or change.
  • Keep one purpose per unit. Split functions or modules when their responsibilities are genuinely distinct, not to meet an arbitrary line limit.
  • Name for intent. Use clear names that fit the surrounding code.
  • Remove repetition carefully. Share logic when its meaning and behavior are the same. Similar-looking rules with different semantics should stay separate.
  • Use types to express existing rules. A type or value object may clarify a real domain concept. Do not use a refactor to add validation or change which inputs are accepted.
  • Keep comments useful. Prefer code that explains what it does. Keep comments that explain intent or a non-obvious constraint; remove stale or commented-out code.
  • Limit the cleanup to the task. Leave nearby code better when the focused change naturally does so; avoid unrelated cleanup.

Common Smells

Smell Possible refactoring
Long function with distinct steps Extract focused functions while keeping the same order and behavior.
Repeated logic with the same meaning Extract a shared helper. Keep different rules separate.
Module or class with unrelated responsibilities Move a responsibility to an existing or appropriately scoped module.
Long parameter list Group parameters only when they form a meaningful unit; update and inspect callers.
Nested conditionals Use guard clauses when they preserve the same checks, order, and outcomes.
Logic that depends heavily on another object's data Move the behavior toward the data owner when that improves cohesion and does not break boundaries.
Primitive values representing a domain concept Introduce a type or value object only when it captures a real invariant or improves safety.
Unexplained literal values Name values when the name adds meaning; ordinary obvious literals need no constant.
Unused code Remove it only after confirming it has no callers or required side effects.

Guard Clause Example

These versions preserve the same checks and error results:

function process(order) {
  if (order) {
    if (order.user) {
      if (order.user.isActive) {
        if (order.total > 0) return processOrder(order);
        return { error: 'Invalid total' };
      }
      return { error: 'User inactive' };
    }
    return { error: 'No user' };
  }
  return { error: 'No order' };
}
function process(order) {
  if (!order) return { error: 'No order' };
  if (!order.user) return { error: 'No user' };
  if (!order.user.isActive) return { error: 'User inactive' };
  if (!(order.total > 0)) return { error: 'Invalid total' };
  return processOrder(order);
}

The total check uses !(order.total > 0) to preserve the original result for values such as NaN.

When to Defer a Refactor

  • There is no clear maintenance problem or expected benefit.
  • The code is stable and unlikely to change.
  • The change cannot be made safely within the available time.
  • Critical behavior lacks adequate protection and a safe characterization check is not practical.

Refactoring Operations

Operation Use
Extract or inline function Give a focused operation a clear name, or remove an unnecessary wrapper.
Rename Clarify intent; update and inspect all references.
Extract class or module Separate a responsibility with a clear boundary.
Introduce parameter object Group cohesive arguments; avoid wrapping unrelated values.
Replace conditional with polymorphism Use when there are real, growing variants and the result is simpler than the conditional.
Replace type code with a type or enum Make existing domain alternatives explicit without changing accepted values.
Replace inheritance with delegation Reduce unwanted coupling when behavior can remain the same.

Do not apply a pattern just because it appears in a catalog. A direct conditional or a small function is often clearer.

Completion Checklist

  • The original behavior and public contract are preserved.
  • The change addresses the identified problem and stays within scope.
  • Relevant callers and references still work.
  • Relevant checks pass, or the remaining verification gap is stated.
  • No unrelated code, new feature, or unnecessary abstraction was added.