Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

refactoringrefactoring 工具

Agent Skill

refactoring 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

256

周安装

11

GitHub Stars

8

下载量

90
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:refactoring(refactoring 工具)
来源仓库:https://github.com/ar4mirez/samuel
仓库路径:skills/refactoring
安装命令:
npx skills add https://github.com/ar4mirez/samuel --skill refactoring
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ar4mirez/samuel --skill refactoring

简介

refactoring 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词快速定位候选结果时使用。

  • 适用于技术债务清理、代码结构优化和复杂度降低,支持函数拆分、重复逻辑消除等重构场景。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装,需结合原始 README 核验具体用法。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写操作。
  • 当前无详细 SKILL.md 内容,需参考仓库中的 Refactoring Skill 了解行为保持和小步变更原则。

SKILL.md

Refactoring Skill

Structured approach to technical debt remediation. Improve code structure while maintaining behavior through incremental, safe changes.


When to Use

TriggerDescription
Guardrail ViolationsFunctions >50 lines, files >300 lines
Complexity ThresholdCyclomatic complexity >10
Code DuplicationSame logic in 3+ places
Quarterly ReviewRegular technical debt assessment
Pre-FeatureBefore adding features to messy code
Post-IncidentAfter bugs caused by confusing code

Refactoring Principles

Golden Rules

  1. Behavior Preservation: Output unchanged after refactoring
  2. Small Steps: One change at a time
  3. Test First: Ensure tests exist before changing
  4. Incremental: Commit after each successful change
  5. Reversible: Easy to roll back if issues arise

When NOT to Refactor

  • During active incident response
  • Without test coverage
  • When deadline is imminent
  • If no clear improvement goal

Prerequisites

Before starting:

  • Code compiles and all tests pass
  • Test coverage exists for target code (>60%)
  • Clear refactoring goal defined
  • Time allocated (refactoring always takes longer)
  • Git working directory is clean

Refactoring Process

Phase 1: Identify Candidates
    ↓
Phase 2: Impact Analysis
    ↓
Phase 3: Plan Refactoring
    ↓
Phase 4: Add Safety Net
    ↓
Phase 5: Execute Incrementally
    ↓
Phase 6: Validate & Document

Phase 1: Identify Candidates

1.1 Automated Detection

Long Functions (>50 lines):

# Find functions over 50 lines (varies by language)
# Example: use linter rules or IDE features

Long Files (>300 lines):

# Find files over 300 lines
find src -name "*.ts" -exec wc -l {} \; | awk '$1 > 300'
find src -name "*.py" -exec wc -l {} \; | awk '$1 > 300'

High Complexity:

# Use complexity analyzers
npx escomplex src/**/*.ts
python -m mccabe src/**/*.py

1.2 Code Smells

SmellSignsPriority
Long Method>50 lines, multiple responsibilitiesHigh
Large Class>300 lines, low cohesionHigh
Feature EnvyMethod uses other class more than ownMedium
Data ClumpsSame group of variables togetherMedium
Primitive ObsessionOveruse of primitives vs objectsMedium
Switch StatementsLarge switch blocksLow
Speculative GeneralityUnused abstractionsLow

1.3 Candidate List

Document identified candidates:

## Refactoring Candidates

### High Priority
| File | Issue | Lines | Impact |
|------|-------|-------|--------|
| src/services/order.ts | Long method: processOrder | 120 → 50 | High |
| src/api/users.ts | Large file | 450 → 200 | High |
| src/utils/validation.ts | Duplication | N/A | Medium |

### Medium Priority
| File | Issue | Lines | Impact |
|------|-------|-------|--------|
| src/models/product.ts | Feature envy | N/A | Medium |
| src/services/email.ts | Complex conditionals | N/A | Medium |

Phase 2: Impact Analysis

2.1 Dependency Mapping

For each candidate, identify:

Target: src/services/order.ts

Dependencies (imports from):
- src/models/order.ts
- src/services/inventory.ts
- src/services/payment.ts

Dependents (imported by):
- src/api/orders.ts
- src/workers/orderProcessor.ts
- tests/services/order.test.ts

Impact radius: 5 files
Risk level: Medium

2.2 Risk Assessment

FactorLowMediumHigh
Test coverage>80%60-80%<60%
Dependents<33-10>10
Business criticalityNon-criticalImportantCritical path
ComplexitySimple renameExtract methodArchitecture change

2.3 Risk Matrix

              Low Effort    High Effort
            ┌────────────┬────────────┐
High Value  │  DO FIRST  │  PLAN      │
            │            │  CAREFULLY │
            ├────────────┼────────────┤
Low Value   │  QUICK WIN │  AVOID     │
            │            │            │
            └────────────┴────────────┘

Phase 3: Plan Refactoring

3.1 Choose Refactoring Technique

SmellTechniqueDescription
Long methodExtract MethodPull out logical chunks
Large classExtract ClassSplit by responsibility
Feature envyMove MethodMove to appropriate class
Data clumpsExtract Parameter ObjectGroup related params
Duplicated codeExtract to shared functionDRY principle
Complex conditionalReplace with polymorphismStrategy pattern
Long parameter listIntroduce Parameter ObjectCreate wrapper class

3.2 Step-by-Step Plan

Example: Extract Method from Long Function

## Refactoring Plan: processOrder()

### Goal
Reduce processOrder() from 120 lines to <50 lines

### Steps
1. [ ] Add characterization tests for current behavior
2. [ ] Extract validateOrder() (lines 15-35)
3. [ ] Verify tests pass
4. [ ] Commit: "refactor: extract validateOrder"
5. [ ] Extract calculateTotals() (lines 40-65)
6. [ ] Verify tests pass
7. [ ] Commit: "refactor: extract calculateTotals"
8. [ ] Extract processPayment() (lines 70-95)
9. [ ] Verify tests pass
10. [ ] Commit: "refactor: extract processPayment"
11. [ ] Extract sendConfirmation() (lines 100-115)
12. [ ] Verify tests pass
13. [ ] Commit: "refactor: extract sendConfirmation"
14. [ ] Final cleanup and documentation
15. [ ] Commit: "refactor: cleanup processOrder"

### Expected Result
- processOrder(): 120 → 25 lines
- New methods: 4
- Total lines: +10 (net increase for clarity)

Phase 4: Add Safety Net

4.1 Characterization Tests

Before refactoring, add tests that capture current behavior:

describe('processOrder - characterization tests', () => {
  it('should match current behavior for valid order', () => {
    const order = createValidOrder();
    const result = processOrder(order);

    // Capture current output exactly
    expect(result).toMatchSnapshot();
  });

  it('should match current behavior for edge cases', () => {
    const edgeCases = [
      createEmptyOrder(),
      createMaxItemOrder(),
      createDiscountedOrder(),
    ];

    edgeCases.forEach(order => {
      expect(processOrder(order)).toMatchSnapshot();
    });
  });
});

4.2 Coverage Check

Ensure adequate coverage before proceeding:

# Check coverage for target file
npm test -- --coverage --collectCoverageFrom="src/services/order.ts"

Minimum Coverage: 60% before refactoring (prefer >80%)

4.3 Checkpoint Commit

Create a checkpoint before starting:

git add .
git commit -m "chore: checkpoint before refactoring processOrder"

Phase 5: Execute Incrementally

5.1 One Change at a Time

Bad: Multiple changes in one commit

# Too much at once - hard to debug if tests fail
git commit -m "refactor: refactor entire order module"

Good: Atomic changes

git commit -m "refactor(order): extract validateOrder method"
git commit -m "refactor(order): extract calculateTotals method"
git commit -m "refactor(order): extract processPayment method"

5.2 Red-Green-Refactor

For each change:

1. Run tests → PASS (green)
2. Make one refactoring change
3. Run tests → Should still PASS (green)
4. If FAIL (red) → Revert and try smaller change
5. If PASS → Commit
6. Repeat

5.3 Common Refactoring Patterns

See references/process.md for detailed code examples including:

  • Extract Method pattern
  • Extract Class pattern
  • Replace Conditional with Polymorphism pattern

Phase 6: Validate & Document

6.1 Final Validation

  • All tests pass
  • Coverage maintained or improved
  • No new linter warnings
  • Performance unchanged (or improved)
  • Behavior identical (check snapshots)

6.2 Document Changes

Update patterns.md (if new pattern emerged):

## Order Processing Pattern

Orders are processed through composable steps:
1. validateOrder() - Input validation
2. calculateTotals() - Price calculations
3. processPayment() - Payment handling
4. sendConfirmation() - Notifications

Create memory entry (if significant):

# Refactoring: Order Processing

**Date**: 2025-01-15
**Files**: src/services/order.ts

## Before
- Single 120-line function
- Difficult to test
- Hard to modify

## After
- 5 focused functions (<30 lines each)
- Easier to test
- Clear responsibilities

## Lessons
- Extract Method is low-risk, high-reward
- Characterization tests prevented regressions

6.3 Final Commit

git add .
git commit -m "refactor(order): complete processOrder decomposition

- Extract validateOrder (20 lines)
- Extract calculateTotals (25 lines)
- Extract processPayment (30 lines)
- Extract sendConfirmation (20 lines)
- Main function now 25 lines (was 120)

No behavior changes. All tests passing."

Refactoring Catalog

Quick Reference

RefactoringWhenEffortRisk
RenameUnclear namingLowLow
Extract MethodLong functionLowLow
Extract VariableComplex expressionLowLow
InlineOver-abstractionLowLow
Extract ClassLarge classMediumMedium
Move MethodFeature envyMediumMedium
Extract Parameter ObjectLong param listMediumLow
Replace Conditional with PolymorphismComplex switchHighMedium
Replace Inheritance with CompositionRigid hierarchyHighHigh

IDE Support

Most refactorings have IDE shortcuts:

ActionVS CodeJetBrains
RenameF2Shift+F6
Extract MethodCtrl+Shift+RCtrl+Alt+M
Extract VariableCtrl+Shift+RCtrl+Alt+V
MoveDrag or F2F6
InlineN/ACtrl+Alt+N

Checklist

Before Refactoring

  • Clear goal defined
  • Tests exist (>60% coverage)
  • Impact analysis complete
  • Step-by-step plan created
  • Checkpoint committed

During Refactoring

  • One change at a time
  • Tests run after each change
  • Commit after each successful change
  • No behavior changes introduced

After Refactoring

  • All tests pass
  • Coverage maintained
  • Code cleaner (measurable)
  • Documentation updated
  • Patterns documented (if applicable)

Related Resources

  • Workflows: code-review.md, testing-strategy.md, troubleshooting.md
  • Detailed Examples: See references/process.md for code patterns
  • Refactoring Book: Martin Fowler's "Refactoring: Improving the Design of Existing Code"

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.36%
按下载量换算31

Claude

31.31%
按下载量换算28

Cursor

17.79%
按下载量换算16

Gemini CLI

8.47%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills