跳到正文
cccskills
免费在 GitHub 公开

refactor

Improve code structure without changing behavior. Use when refactoring, restructuring, simplifying, or extracting code. Also for reducing duplication, renaming for clarity, or addressing code smells. Enforces one change → test → commit cycle. NOT for style/formatting (use /lint), features, or bug fixes.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md8.1 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Refactoring

Improve code structure without changing behavior. One small step at a time.

Iron Law: ONE REFACTORING → TEST → COMMIT. Never batch changes.

When to Use

Answer IN ORDER. Stop at first match:

  1. User says "refactor", "clean up", "restructure"? → Use this skill
  2. User asks to "extract", "rename", "simplify"? → Use this skill
  3. Code smell identified? → Use this skill
  4. User wants to add feature or fix bug? → Skip (use tdd-enforcer)
  5. User wants formatting/style fixes? → Skip (use /lint)

Code smells (common triggers):

  • Duplicated code (same logic in multiple places)
  • Long function (>30 lines, doing too much)
  • Magic numbers/strings (unexplained literals)
  • Deep nesting (>3 levels of indentation)
  • Dead code (unused functions, unreachable branches)
  • Poor naming (unclear what something does)

Phase 1: ASSESS

Is this actually refactoring?

User IntentAction
"Make this cleaner"✓ Refactoring
"Add validation"✗ New behavior → tdd-enforcer
"Fix this bug"✗ Bug fix → tdd-enforcer or systematic-debugger
"Format this code"✗ Style → /lint

If not refactoring: Explain and suggest correct approach.


Phase 2: PROTECT

Does the code have tests?

CoverageAction
Well-testedSkip to Phase 3
Partial coverageAdd characterization tests for untested parts
No testsAdd characterization tests first

When writing characterization tests: Characterization tests are still tests — apply behavioral testing principles (assert on what the system does, not how).

Characterization Tests

Capture current behavior before refactoring:

// Characterization test - captures ACTUAL behavior
it("processOrder returns current behavior", () => {
  const result = processOrder({ items: [], user: null });
  // Whatever it returns NOW is the expected value
  expect(result).toEqual({ status: "empty", total: 0 });
});

Purpose: Safety net, not specification. Test what the code DOES, not what it SHOULD do.


Phase 3: REFACTOR

Iron Law: ONE refactoring at a time. Run tests after EVERY change.

Refactoring Catalog

Tier 1 - Always Safe (no behavior change possible):

SmellRefactoringExample
Unclear nameRenamed → discountAmount
Long functionExtract FunctionPull 10 lines into calculateTax()
Unnecessary variableInline VariableRemove temp = x; return temp;
Misplaced codeMove FunctionMove validate() to Validator class
// ❌ Before: unclear name
const d = price * 0.2;

// ✅ After: Rename
const discountAmount = price * 0.2;

Tier 2 - Safe with Tests (low risk if tests exist):

SmellRefactoringExample
Repeated expressionExtract Variableorder.items.length > 0 → const hasItems = ...
Complex conditionalDecompose ConditionalExtract if branches to named functions
Nested conditionalsGuard ClausesEarly returns instead of deep nesting
Magic literalReplace Magic Literal0.2 → VIP_DISCOUNT_RATE
Unused codeRemove Dead CodeDelete unreachable branches
// ❌ Before: nested conditionals
function getDiscount(user) {
  if (user) {
    if (user.isVIP) {
      return 0.2;
    } else {
      return 0.1;
    }
  }
  return 0;
}

// ✅ After: Guard Clauses
function getDiscount(user) {
  if (!user) return 0;
  if (user.isVIP) return 0.2;
  return 0.1;
}

Tier 3 - Requires Care (higher risk, break into smaller steps):

SmellRefactoringCaution
God classExtract ClassDo incrementally, move one method at a time
Type-checking conditionalsReplace with PolymorphismRequires class hierarchy
Too many parametersIntroduce Parameter ObjectChanges function signature
Complex loopReplace Loop with PipelineEnsure equivalent behavior

Tie-breaker: If multiple refactorings apply, choose smallest scope first (Rename < Extract Variable < Extract Function < Extract Class).


Phase 4: VERIFY

After each refactoring:

  1. Run tests - Must pass
  2. If tests pass: Commit with refactor: [what changed]
  3. If tests fail: Revert immediately

Revert Protocol

git checkout -- <changed-files>

After revert:

  • Was the refactoring too large? → Try smaller step
  • Did it accidentally change behavior? → Reconsider approach
  • DO NOT attempt to "fix" a failed refactoring

After 2 Failed Attempts

STOP. Ask user:

"I've attempted this refactoring twice and tests keep failing. This suggests either:

  1. The refactoring is too large (need smaller steps)
  2. The code has hidden dependencies
  3. Tests are brittle

How would you like to proceed?"


Phase 5: ITERATE

More refactoring needed?
├─ Yes → Return to Phase 3 (one more refactoring)
└─ No → Done
    ├─ Run `/audit` to verify no dead code or new issues
    └─ Report: "Refactoring complete. Changes: [summary]"

Audit catches: Dead code left behind, new duplication (should decrease!), architecture violations.


Edge Cases

Partial test coverage:

  • Identify which functions are tested vs untested
  • Add characterization tests only for code you're about to refactor
  • Don't boil the ocean - test what you touch

Refactoring reveals a bug:

  • STOP refactoring
  • Note the bug location
  • Ask user: "Found potential bug at X. Fix it now (switching to tdd-enforcer) or continue refactoring?"

User requests large refactoring:

  • Break into steps: "I'll refactor this incrementally. First: [step 1]"
  • Complete each step fully before next
  • Never batch multiple refactorings in one edit

Anti-Patterns

Don'tDo
Batch multiple refactoringsOne refactoring → test → commit
"Fix" a failed refactoringRevert, then try smaller step
Refactor without testsAdd characterization tests first
Change behavior during refactorThat's a feature/fix, not refactoring
Skip the commitCommit after every green test

Key Takeaways

  1. One change at a time - Never batch refactorings
  2. Tests before refactoring - No safety net = no refactoring
  3. Revert on failure - Don't fix, revert and retry smaller
  4. Commit after each success - refactor: [description]
  5. Smallest scope first - Rename < Extract < Move < Restructure
  6. Audit when done - Run /audit to verify no dead code or new issues

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

audit

免费

Run comprehensive code audit for architecture, dead code, and test quality. Use when reviewing overall codebase health, checking for architectural violations, or before marking a feature complete.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

bdd

免费

Behavior-first feature development — use when building new capabilities, continuing feature work, or when work introduces new state or multiple user flows. Discovers desired behavior through examples and scenarios before implementation. Do NOT use for bug fixes, typos, or small isolated changes.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

Use when the user wants to explore options, weigh approaches, or think through uncertainty before committing to a direction. Collaborative brainstorming and rubber ducking — divergence-first thinking partner.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

Kill zombie dev servers and test processes. Use when ports are blocked, processes are hanging, or test runners won't start.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

debug

免费

Root cause debugging before fixes. Use when investigating bugs, diagnosing test failures, troubleshooting unexpected behavior, or when previous fix attempts failed. Enforces investigate-first discipline.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

elicit

免费

Extract tacit knowledge through non-obvious microquestions — things only the user knows that can't be found in code, docs, or research. Use when you're about to guess at intent, context, or constraints during SAFEWORD's understanding flow. Also use when user says 'ask me', 'what do you need to know', or when another skill (bdd, brainstorm, debug) needs user context before proceeding. Do NOT use for questions answerable by reading the codebase or searching the web.

中文简介正在准备中。当前显示原文说明。

TheMostlyGreat/mythos192026年6月14日 更新

查看 TheMostlyGreat 的全部技能

报告此技能的问题