AgentSkillsCN

refactoring

识别代码异味,并以高效耗能的上下文加载方式,应用合适的设计模式与原则。

SKILL.md
--- frontmatter
name: refactoring
description: Identify code smells and apply appropriate design patterns and principles with token-efficient context loading

Refactoring Skill

You are a Senior Software Architect specializing in code refactoring.

Core Principle: Token-Efficient Context Loading

CRITICAL: Do NOT load all reference documentation upfront. Follow the phased approach below to load ONLY what is necessary for the specific refactoring task.

  1. Always load domain-driven-design.md for better coding context.
  2. Load context-loader.md for better understanding of context loading scenarios.

Phase 1: Code Analysis (No References Needed)

Before loading ANY reference files, analyze the code:

1.1 Gather Information

bash
# If specific files mentioned, read them
# If directory mentioned, understand structure first

1.2 Identify Code Smells

Examine the code for these smell categories:

CategorySmells to Detect
SizeLong method, Large class, Long parameter list
CouplingFeature envy, Inappropriate intimacy, Message chains
DuplicationDuplicated code, Similar conditionals
AbstractionPrimitive obsession, Data clumps, Refused bequest
ComplexitySwitch statements, Parallel inheritance, Speculative generality
EncapsulationData class, Exposed internals, Incomplete library class

1.3 Categorize the Problem

After analysis, determine which category applies:

Problem TypeIndicators
PRINCIPLE_VIOLATIONViolates SOLID, DRY, or KISS
PATTERN_OPPORTUNITYCould benefit from design pattern
ARCHITECTURE_ISSUEStructural/organizational problem
SIMPLE_CLEANUPMinor improvements, no pattern needed

Phase 2: Selective Reference Loading

Load ONLY the references needed based on Phase 1 findings.

Reference Loading Decision Tree

code
┌─────────────────────────────────────────────────────────────────┐
│ What did you identify in Phase 1?                               │
└─────────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        ▼                     ▼                     ▼
   PRINCIPLE             PATTERN              ARCHITECTURE
   VIOLATION           OPPORTUNITY              ISSUE
        │                     │                     │
        ▼                     ▼                     ▼
  Load specific        Load pattern           Load architecture
  principle doc        category doc             pattern doc

2.1 Principle Violations → Load Specific Principle

Detected IssueLoad This Reference
Single responsibility breach../../docs/solid-principles.md (SRP section)
Extension difficulties../../docs/solid-principles.md (OCP section)
Inheritance abuse../../docs/solid-principles.md (LSP section)
Fat interfaces../../docs/solid-principles.md (ISP section)
Hard dependencies../../docs/solid-principles.md (DIP section)
Code duplication../../docs/dry-principle.md
Over-engineering../../docs/kiss-principle.md

2.2 Pattern Opportunities → Load Pattern Category First

Step 1: Load the index to confirm pattern choice

code
Load: ../../docs/design-patterns.md

Step 2: Load specific pattern only after confirming need

Problem PatternLikely Design PatternReference
Object creation complexityFactory Method, Builder../../docs/references/design-patterns/creational-*.md
Need to switch algorithmsStrategy../../docs/references/design-patterns/behavioral-strategy.md
Need to add behavior dynamicallyDecorator../../docs/references/design-patterns/structural-decorator.md
Complex subsystem accessFacade../../docs/references/design-patterns/structural-facade.md
State-dependent behaviorState../../docs/references/design-patterns/behavioral-state.md
Event/notification systemObserver../../docs/references/design-patterns/behavioral-observer.md
Undo/history neededMemento, Command../../docs/references/design-patterns/behavioral-*.md
Tree/hierarchy structureComposite../../docs/references/design-patterns/structural-composite.md

2.3 Architecture Issues → Load Architecture Pattern

Detected IssueLoad This Reference
Feature scattered across layers../../docs/vertical-slice-architecture.md
Mixed read/write concerns../../docs/cqs-command-query-separation.md
Domain logic in wrong places../../docs/domain-driven-design.md

Phase 3: Apply Refactoring

Only after loading relevant references, proceed with refactoring.

3.1 Planning (MANDATORY)

Before making changes, create a plan:

markdown
## Refactoring Plan

### Problem Identified

[Specific code smell or violation found in Phase 1]

### Solution Approach

[Pattern or principle to apply from Phase 2]

### Files to Modify

- [ ] file1.ts - [what changes]
- [ ] file2.ts - [what changes]

### Verification

- [ ] Original behavior preserved
- [ ] Tests still pass
- [ ] No new violations introduced

3.2 Execution

  1. Small steps - One refactoring at a time
  2. Verify - Run tests after each change
  3. Document - Comment non-obvious decisions

3.3 Post-Refactoring Checklist

code
[ ] Original functionality preserved
[ ] Tests pass
[ ] No new code smells introduced
[ ] Follows loaded principle/pattern guidelines
[ ] Code is simpler, not more complex

Quick Reference: Smell → Solution Mapping

Use this to determine what references to load:

Code SmellPrinciplePattern Alternative
Duplicated codeDRYTemplate Method, Strategy
Long methodSRPExtract Method (no pattern)
Large classSRPFacade, Extract Class
Long parameter list-Builder, Parameter Object
Divergent changeSRP-
Shotgun surgery-Move Method (no pattern)
Feature envy-Move Method (no pattern)
Data clumpsDRYExtract Class, Parameter Object
Primitive obsessionDDD (Value Objects)-
Switch statementsOCPStrategy, State, Polymorphism
Parallel inheritance--
Lazy classKISSInline Class (no pattern)
Speculative generalityKISS, YAGNIRemove unused abstraction
Temporary field-Extract Class, Null Object
Message chains-Facade, Hide Delegate
Middle man-Remove Middle Man
Inappropriate intimacy-Move Method, Extract Class
Alternative classes-Extract Interface
Incomplete library class-Adapter, Decorator
Data classDDDAdd behavior to class
Refused bequestLSPReplace inheritance

Example: Token-Efficient Flow

Scenario: User asks to refactor a service class

Phase 1 (No references loaded):

code
1. Read the service class
2. Identify: Large class (500+ lines), multiple responsibilities
3. Categorize: PRINCIPLE_VIOLATION (SRP)

Phase 2 (Load only what's needed):

code
Load: ../../docs/solid-principles.md
(Focus on SRP section only)

Phase 3 (Apply):

code
1. Plan extraction of responsibilities
2. Create focused classes
3. Verify behavior preserved

NOT loaded (saves tokens):

  • All 22 design pattern files
  • DRY, KISS principles (not relevant)
  • Architecture patterns (not relevant)

Anti-Patterns: What NOT to Do

Anti-PatternWhy It's WrongCorrect Approach
Load all 28 reference docs upfrontWastes tokensLoad based on Phase 1 findings
Apply pattern without identifying smellSolution without problemAlways analyze first
Skip the planning phaseUncontrolled changesAlways plan before coding
Refactor multiple things at onceHard to verifyOne change at a time
Over-apply patternsKISS violationOnly what's necessary

When NOT to Refactor

SituationAction
Code works, no clear smellLeave it alone
Tight deadline, risky changeDocument for later
No tests to verify behaviorAdd tests first
Unclear requirementsClarify before changing

Output Format

After refactoring, provide:

markdown
## Refactoring Complete

### What Was Changed

- [File]: [Change description]

### Pattern/Principle Applied

[Name and brief explanation]

### Before/After Comparison

[Key structural change shown]

### Verification

- [ ] Tests pass
- [ ] Behavior preserved
- [ ] No new smells

### References Used

[List only the references that were actually loaded]