refactoring

기존 코드의 안전한 리팩토링. Characterization Test로 동작 보존하며 구조 개선

9 stars

Best use case

refactoring is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

기존 코드의 안전한 리팩토링. Characterization Test로 동작 보존하며 구조 개선

Teams using refactoring should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/refactoring/SKILL.md --create-dirs "https://raw.githubusercontent.com/ssiumha/dots/main/prompts/skills/refactoring/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/refactoring/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How refactoring Compares

Feature / AgentrefactoringStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

기존 코드의 안전한 리팩토링. Characterization Test로 동작 보존하며 구조 개선

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Refactoring

기존 코드를 안전하게 리팩토링하는 ANALYZE-PRESERVE-IMPROVE 워크플로우.

## tidy와의 구분

| | tidy | refactoring |
|--|------|-------------|
| 규모 | 분 단위 소규모 정리 | 시간~일 단위 구조 변경 |
| 테스트 | 기존 테스트 의존 | **Characterization Test 새로 작성** |
| 범위 | 단일 패턴 (guard clause, dead code 등) | 모듈 추출, 클래스 분리, API 마이그레이션 |
| 커밋 | 1 tidying = 1 commit | 단계별 incremental commit |

## tdd와의 구분

| | tdd | refactoring |
|--|---------------|-------------|
| 대상 | **새 기능** (코드 없음) | **기존 코드** (동작 있음) |
| 테스트 | Specification Test (기대 동작 정의) | Characterization Test (현재 동작 캡처) |
| 사이클 | RED-GREEN-REFACTOR | ANALYZE-PRESERVE-IMPROVE |

## ANALYZE-PRESERVE-IMPROVE Cycle

### Phase 1: ANALYZE

현재 코드 구조를 파악하고 리팩토링 대상을 식별한다.

**구조 분석**:
- 모듈 의존성, import 패턴 (`/vis-graph` 활용)
- 결합도 메트릭 (`/code-metrics` 활용)
- 데이터 흐름, 공유 상태, 결합 지점

**문제 패턴 식별** (ast-grep 활용):
- God class: 너무 많은 메서드/책임
- Feature envy: 다른 클래스 데이터를 과도하게 사용
- Long parameter list: 누락된 추상화
- Duplicate code: 모듈 간 중복 패턴

**산출물**: 현재 구조 + 문제 영역 + 리팩토링 대상 + 리스크 평가

### Phase 2: PRESERVE

변경 전 안전망을 구축한다. **이 단계를 건너뛰지 않는다.**

**Characterization Test 작성**:
1. 핵심 코드 경로를 식별
2. 경로를 실행하는 테스트 작성
3. 테스트를 먼저 실패시켜 **실제 출력**을 확인
4. 실제 출력을 기대값으로 업데이트
5. 놀라운 동작이 있으면 문서화

> Characterization Test는 "정답"을 검증하는 게 아니라 **"현재 동작"**을 기록한다.
> 리팩토링 후 이 테스트가 깨지면 동작이 바뀐 것이다.

네이밍: `test_characterize_{component}_{scenario}`

> Characterization Test의 품질은 `/principles check TEST-BEHAVIOR` (외부 행위 기반 검증) 및 `/principles check TEST-SMELLS` (Sensitive Equality — 부동소수점·직렬화 포맷 주의) 참조.

**Behavior Snapshot** (복잡한 출력일 때):
- API 응답, 직렬화 출력, 상태 변환, 에러 메시지

**Safety Net 검증**:
- 기존 테스트 100% 통과
- 새 characterization test가 리팩토링 대상을 커버
- Flaky 테스트 없음 확인

### Phase 3: IMPROVE

**한 번에 큰 변경을 하지 않는다.** 패턴:

```
가장 작은 구조 변경 → 전체 테스트 → 실패 시 즉시 revert → 성공 시 commit → 반복
```

**안전한 리팩토링 패턴**:
- **Extract Method**: 반복 코드 블록 또는 긴 메서드 → 명명된 함수로 분리
- **Extract Class**: 다중 책임 클래스 → 관련 메서드/필드를 새 클래스로 이동 (원본 API는 위임으로 유지)
- **Move Method**: Feature envy → 데이터가 있는 클래스로 이동
- **Inline**: 불필요한 간접 참조 제거
- **Rename**: ast-grep rewrite로 모든 참조를 원자적으로 변경

**각 변환 후 검증**:
1. Unit test (빠른 피드백)
2. Characterization test (동작 보존 확인)
3. 새 warning/error 없음 확인

## 실행 순서

```
1. 리팩토링 범위 확인 (SPEC 또는 사용자 요청)
2. ANALYZE: 대상 코드 구조 분석
3. PRESERVE: Characterization Test 작성 + 기존 테스트 통과 확인
4. IMPROVE: 점진적 변환 (각 단계마다 테스트 + 커밋)
5. 검증: 전후 메트릭 비교 + 모든 테스트 통과
```

## Behavior Preservation 원칙

리팩토링의 황금률: **관찰 가능한 동작이 전후 동일해야 한다.**

- 기존 테스트 전부 통과
- API 계약 동일
- 부작용(side effects) 동일
- 성능 특성이 허용 범위 내

## Troubleshooting

**테스트 실패 시**: 즉시 revert → 어떤 테스트가 왜 실패했는지 분석 → 더 작은 단위로 재시도

**Characterization Test가 flaky**: 비결정적 요소 식별 → 외부 의존성 mock → 시간/순서 의존 제거

**성능 저하**: 전후 프로파일링 → 핫 패스 확인 → 최적화 또는 트레이드오프 문서화

## See Also

- `/tidy` — 분 단위 소규모 코드 정리
- `/plan-review tdd` — 새 기능의 테스트 주도 개발
- `/code-metrics` — 결합도/복잡도 정량 측정
- `/vis-graph` — 파일 간 의존성 시각화
- `/strategic-thinking` — 리팩토링 범위 결정 시 체계적 판단

> Origin: moai-adk workflow-ddd (ANALYZE-PRESERVE-IMPROVE cycle) 기반, dots 스타일로 재구성

Related Skills

tree-sitter

9
from ssiumha/dots

AST parsing, S-expression queries, tag extraction via tree-sitter CLI. Use when parsing code into AST, extracting tags, visualizing syntax trees, or performing structural analysis beyond ast-grep.

tidy

9
from ssiumha/dots

Performs small structural code cleanups (tidyings). Use when preparing code changes, removing dead code, reducing nesting, or cleaning up before feature work.

task-naming

9
from ssiumha/dots

CLI command naming convention for Justfile and Makefile. Enforces GAT (group-action-target) word order, grouped listing, mandatory descriptions. Use when creating Justfile recipes, Makefile targets, or reviewing task runner configs for naming consistency. Also use when asking "what should I name this command?" for task runners. Do NOT use for npm scripts, mise tasks, or Claude Code skill naming.

strategic-thinking

9
from ssiumha/dots

체계적 의사결정 프레임워크. First Principles, Trade-off 분석, Cognitive Bias 점검

security

9
from ssiumha/dots

Security expert hub. Code security review (OWASP Top 10, injection, XSS, credentials), vulnerability assessment (KISA 292 items, Unix/Windows server, web pentest, network, DBMS, cloud), ISMS-P certification (101 items, checklist, implementation plan), EFSR financial regulation compliance (전자금융감독규정, 12 articles). 보안 리뷰, 취약점 점검, 인증 준비, 금융규정 준수.

reflect

9
from ssiumha/dots

방향 수정 신호 감지 및 세션 전체 회고. Use when detecting course correction signals ("아니/잠깐/근데"), session retrospective, or reviewing overall progress. /reflect 또는 "회고해줘"로 수동 호출.

recall

9
from ssiumha/dots

Load context from Obsidian vault (journals, session pages) and JSONL session history. Vault 위치/구조는 `documentation` skill 참조. Temporal queries scan JSONL by date, topic queries use ir BM25. Use when "recall", "어제 뭐 했지", "what did we work on", "이전 작업", "session history".

qmd

9
from ssiumha/dots

Searches local markdown notes and documents using ir CLI. Use when searching notes, querying documents, managing collections, or retrieving document content.

qa

9
from ssiumha/dots

기능별 QA 체크리스트 생성, 수동 테스트 실행, 결과 기록. Use when QA 테스트, 체크리스트 만들기, 수동 검증, 기능 확인, qa 진행, checklist. Do NOT use for automated test code (use plan-review tdd / code-review instead) or BDD spec (use plan-review bdd instead).

principles

9
from ssiumha/dots

소프트웨어 공학 원칙 바스켓. 원칙 카탈로그 열람, 코드/설계/프로세스/테스트의 원칙 준수도 평가, 위반 식별 및 개선 가이드. Use when 원칙 평가, 원칙 점검, 원칙 검증, principles check, 코드 품질 근본 진단, 설계 원칙 리뷰, 아키텍처 원칙 점검, 프로세스 원칙 점검, 테스트 원칙 점검, 테스트 설계, or when other review skills need a principled foundation. Do NOT use for specific code review (use code-review), security audit (use security), or strategic decisions (use strategic-thinking).

ppt

9
from ssiumha/dots

Generates PowerPoint architecture diagrams with auto-layout and orthogonal routing using PPTXGenJS. Use when creating AWS architecture diagrams, infrastructure layouts, system design slides, IDC 구성도, or any diagram that needs boxes with right-angle connectors in .pptx format. Also use when 아키텍처 다이어그램, 인프라 구성도, PPT 생성, 구성도 만들기, 슬라이드 자동 생성. Do NOT use for simple text-only presentations (use PowerPoint directly), data charts (use data-investigation), or ASCII/Mermaid diagrams (use diagram skill).

plan-review

9
from ssiumha/dots

Reviews execution plans for scope, codebase validity, risk, and completeness before implementation. Use when reviewing a plan, 계획 리뷰, 계획 검증, checking plan quality before execution, or "리뷰해줘" after plan mode. Includes TDD, BDD, DDD methodology domains.