MCP HubMCP Hub
SKILL·9FEE0E

refactoring-patterns

wondelai
업데이트됨 15 days ago
3 조회
2,020
206
2,020
GitHub에서 보기
테스팅testingapidesign

정보

이 기술은 동작을 보존하면서 코드 구조를 개선하기 위해 명명된 리팩토링 변환(예: 메서드 추출 또는 조건문 교체)을 적용합니다. 이는 레거시 코드를 정리하거나 새로운 기능을 준비할 때 코드 스멜, 기술 부채 또는 특정 리팩토링 작업이 언급되면 트리거됩니다. 이 프레임워크는 안전한 변환 시퀀스와 함께 테스트 주도 접근 방식을 체계적으로 제공합니다.

빠른 설치

Claude Code

추천
기본
npx skills add wondelai/skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/wondelai/skills
Git 클론대체
git clone https://github.com/wondelai/skills.git ~/.claude/skills/refactoring-patterns

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Refactoring Patterns Framework

A disciplined approach to improving the internal structure of existing code without changing its observable behavior. Every refactoring follows the same loop: verify tests pass, apply one small structural change, verify tests still pass.

Core Principle

Refactoring is not rewriting. It is a sequence of small, behavior-preserving transformations, each backed by tests. You never change what the code does — only how it is organized. Big-bang rewrites fail because they combine structural change with behavioral change, making it impossible to know which broke things.

The foundation: Bad code is a natural consequence of delivering under time pressure, not a character flaw. Code smells are objective signals of degraded structure; the smell catalog tells you where to look, and the refactoring catalog tells you what to do.

Scoring

Goal: 10/10. Score structural quality by how many of the eight Quick Diagnostic rows pass — score = round(passed / 8 × 10), adjusting down when a single smell is severe. Bands:

  • 9-10: no obvious smells remain, each function does one thing, names reveal intent, duplication is eliminated, conditionals use polymorphism where apt, and tests cover the refactored paths.
  • 5-6: a few smells remain (a Long Method, some duplication) but structure is mostly sound.
  • ≤3: pervasive smells — tangled conditionals, God classes, duplication everywhere — or no tests to refactor safely.

Always state the current score, name the smells driving it down, and list the specific refactorings needed to reach 10/10.

The Refactoring Patterns Framework

Six areas of focus for systematically improving code structure:

1. Code Smells as Triggers

Core concept: Code smells are surface indicators of deeper structural problems — not bugs, but signals that the design makes code harder to understand, extend, or maintain. Each smell maps to named refactorings that fix it.

Why it works: Named smells give teams objective criteria instead of subjective "I don't like this" — "This is Feature Envy" points directly at the fix.

Key insights:

  • Smells cluster into five families: Bloaters, Object-Orientation Abusers, Change Preventers, Dispensables, Couplers
  • Long Method is the most common smell; Duplicate Code is the most expensive
  • A method that needs a comment to explain what it does is a smell — extract and name the block instead
  • Shotgun Surgery (one change, many classes) and Divergent Change (one class, many reasons to change) are opposite signals of misplaced responsibilities
  • Primitive Obsession — raw strings/ints instead of small domain objects — spreads errors and duplication

Code applications:

ContextPatternExample
Method > 10 linesExtract MethodPull loop body into calculateLineTotal()
One change touches many classes (Shotgun Surgery)Move Method/FieldGather the scattered behavior into one class
Same params in many methodsIntroduce Parameter ObjectstartDate, endDateDateRange
Copy-pasted logicExtract Method + Pull Up MethodShare via common method or base class

See references/smell-catalog.md when you need to name a smell and its fix — all five families (Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers) with detection heuristics and the refactoring each maps to.

2. Composing Methods

Core concept: Most refactoring starts here: break long methods into smaller, well-named pieces that read like prose — high-level steps delegating to clearly named helpers.

Why it works: Short methods with intention-revealing names eliminate comments, make bugs obvious at a glance, and enable reuse; a method call costs nothing to read when the name says everything.

Key insights:

  • Extract Method is the single most important refactoring — master it first
  • Urge to write a comment? Extract the block and use the comment as the method name
  • Inline Method when the body is as clear as the name — indirection without value is noise
  • Replace Temp with Query for computed values used in multiple places; Split Temporary Variable when one temp serves two purposes
  • Replace Method with Method Object when locals are too tangled to extract — they become fields

Code applications:

ContextPatternExample
Block with a commentExtract Method// check eligibilityisEligible()
Temp used onceInline VariableDrop const price = order.getPrice()
Trivial delegating methodInline MethodInline return deliveries > 5 if used once
Method with many tangled localsReplace Method with Method ObjectLocals become fields in a new class

See references/composing-methods.md when applying any method-level transformation — step-by-step mechanics and before/after code for Extract/Inline Method, Extract/Inline Variable, Replace Temp with Query, Split Temporary Variable, and Replace Method with Method Object.

3. Moving Features Between Objects

Core concept: The key OO design decision is where responsibilities live. When Feature Envy, excessive coupling, or unbalanced class sizes show a method or field is in the wrong class, move it where it belongs.

Why it works: A method placed away from the data it uses creates invisible cross-class dependencies, so one logical change ripples across many files — Shotgun Surgery. Co-locating method and data confines the change to one class.

Key insights:

  • Move Method when a method uses more of another class's features than its own; Move Field likewise
  • Extract Class when one class does two things — split along the axis of change; Inline Class when one does too little
  • Hide Delegate enforces the Law of Demeter; Remove Middle Man undoes it when forwarding becomes the whole class
  • Resolve that tension case by case: hide the delegate when the chain is unstable, remove the middle man when it's pure forwarding

Code applications:

ContextPatternExample
Method envies another classMove MethodcalculateShipping() from Order to ShippingPolicy
God class 500+ linesExtract ClassPull Address fields/methods into own class
Client calls a.getB().getC()Hide DelegateAdd a.getCThroughB()
Class only forwards callsRemove Middle ManLet client call the delegate directly

See references/moving-features.md when deciding where a responsibility belongs — mechanics for Move Method/Field, Extract/Inline Class, Hide Delegate, and Remove Middle Man.

4. Organizing Data

Core concept: Raw data — magic numbers, exposed fields, integer type codes — creates subtle bugs and scatters domain knowledge. Replace primitives with objects that encapsulate behavior and enforce invariants.

Why it works: An int amount has no rounding rules or currency code; a Money object encapsulates all of it, so business rules live in one place and the type system catches errors at compile time.

Key insights:

  • Replace Magic Number with Symbolic Constant — the simplest data refactoring; it names intent
  • Replace Data Value with Object cures Primitive Obsession (EmailAddress, Money, Temperature)
  • Encapsulate Field and Encapsulate Collection — never expose raw fields or mutable internal lists
  • Replace Type Code with Subclasses when the code affects behavior; with Strategy when subclassing is impractical
  • Change Value to Reference when you need identity semantics (one shared Customer, not copies)

Code applications:

ContextPatternExample
if (status == 2)Replace Magic Numberif (status == ORDER_SHIPPED)
String email passed everywhereReplace Data Value with ObjectEmailAddress class with validation
Getter returns mutable listEncapsulate CollectionReturn Collections.unmodifiableList(items)
int typeCode with switchReplace Type Code with SubclassesEmployeeEngineer, Manager

See references/organizing-data.md when replacing primitives with objects — mechanics for Replace Data Value with Object, Change Value to Reference, Replace Magic Number, Encapsulate Field/Collection, and the Replace Type Code variants.

5. Simplifying Conditional Logic

Core concept: Deeply nested if/else trees, long switches, and scattered null checks are the hardest code to read and the most bug-prone. Named refactorings decompose, consolidate, and replace conditionals with clearer structures.

Why it works: A six-branch conditional forces readers to simulate every path mentally; well-named extracted branches are self-documenting, and polymorphism eliminates whole categories of "forgot this case" bugs.

Key insights:

  • Decompose Conditional: extract condition, then-branch, and else-branch into named methods
  • Consolidate Conditional Expression: merge conditions with the same result into one named check
  • Replace Nested Conditional with Guard Clauses: handle edge cases early and return, keeping the main path unindented
  • Replace Conditional with Polymorphism is the gold standard for type-based conditionals
  • Introduce Special Case (Null Object) eliminates scattered if (x == null) checks; Introduce Assertion makes assumptions fail fast

Code applications:

ContextPatternExample
Long if with complex conditionDecompose ConditionalExtract isSummer(date) and summerCharge()
Deeply nested if/elseReplace with Guard ClausesEdge cases first, return early, flat main path
Switch on object typeReplace Conditional with PolymorphismEach type implements its own calculatePay()
if (customer == null) everywhereIntroduce Special CaseNullCustomer with safe default behavior

See references/simplifying-conditionals.md when untangling branches — before/after examples for Decompose/Consolidate Conditional, Guard Clauses, Replace Conditional with Polymorphism, Special Case, and Assertions.

6. Safe Refactoring Workflow

Core concept: Refactoring is only safe when wrapped in tests. The workflow is mechanical: run tests (green), apply one small transformation, run tests (green), commit. If tests go red, revert — don't debug a broken refactoring.

Why it works: Small steps make the failure obvious (it was the last thing you did) and reverting costs seconds; debugging a failed big-bang rewrite costs days.

Key insights:

  • Rule of Three: tolerate duplication once, note it twice, refactor on the third occurrence
  • Preparatory refactoring: restructure to make the feature easy before adding it; comprehension and litter-pickup refactoring keep code improving as you read and touch it
  • When NOT to refactor: rewriting is easier, no tests and adding them isn't feasible, or the code will be deleted soon
  • Refactor for clarity first, then profile and optimize the measured bottleneck — clear code is easier to tune
  • Branch by Abstraction and Parallel Change enable large refactorings in production without long-lived branches

Code applications:

ContextPatternExample
About to add a featurePreparatory RefactoringClean the insertion point first
Third copy of same logicRule of ThreeExtract shared logic now
Large API change in productionBranch by AbstractionAdd abstraction layer, migrate callers, remove old path
Renaming a widely-used methodParallel ChangeAdd new, deprecate old, migrate, remove

See references/refactoring-workflow.md before a large or risky refactoring — the full green-to-green cycle, when (not) to refactor, performance, Branch by Abstraction, and Parallel Change.

Common Mistakes

MistakeWhy It FailsFix
Refactoring without testsNo safety net to detect behavior changeWrite characterization tests first
Big-bang rewriteMixes structural and behavioral change; undebuggableSmallest possible steps, tests after each
Refactoring while adding featuresTwo hats at once — neither change verifiableRefactor first (commit), then add feature (commit)
Renaming without updating callersBroken build or dead codeUse IDE rename; search all references
Extracting too many tiny methodsIndirection without clarity when names are poorEach name must remove the need to read the body
Ignoring the smell catalogReinvents fixes instead of applying proven recipesLearn named smells; each maps to refactorings
Refactoring doomed codePolish on condemned code is wasteCheck the code's lifespan justifies the investment
Optimizing while refactoringConflates clarity with performanceClarity first, then profile, then optimize hot path

Quick Diagnostic

QuestionIf NoAction
Do tests pass before you start?No safety netWrite or fix tests first — never refactor red
Can you name the smell you're fixing?Refactoring by instinct, not catalogIdentify the smell, apply its prescribed refactoring
Is each method under ~10 lines?Long Methods likelyExtract Method into named steps
Does each class have one reason to change?Divergent Change or Large ClassExtract Class to separate responsibilities
Are there duplicated code blocks?The most expensive smellExtract shared logic into common method/base class
Do conditionals use polymorphism where apt?Switch Statements remainReplace Conditional with Polymorphism
Are you committing after each step?Risk losing work, mixing changesCommit after every green-to-green transformation
Is the code easier to read after your change?Refactoring added complexityRevert and try a different approach

Further Reading

The definitive guides to improving existing code:

About the Author

Martin Fowler is Chief Scientist at Thoughtworks, a signatory of the Agile Manifesto, and author of Refactoring: Improving the Design of Existing Code (1999; 2nd edition 2018), which introduced catalog-based, named refactorings to mainstream development. His catalog underpins the automated refactoring tools in every major IDE.

GitHub 저장소

wondelai/skills
경로: plugins/wondelai-skills/skills/refactoring-patterns
0
agent-skillsai-skillsbusinessclaude-codeclaude-code-marketplaceclaude-code-plugin
FAQ

자주 묻는 질문

refactoring-patterns Skill이란 무엇인가요?

refactoring-patterns은(는) wondelai이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 refactoring-patterns 관련 작업을 수행할 수 있게 합니다.

refactoring-patterns은(는) 어떻게 설치하나요?

이 페이지의 설치 명령을 사용하세요. refactoring-patterns을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.

refactoring-patterns은(는) 어떤 카테고리에 속하나요?

refactoring-patterns은(는) 테스팅 카테고리에 속합니다.

refactoring-patterns은(는) 무료로 사용할 수 있나요?

네. refactoring-patterns은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.

연관 스킬

evaluating-llms-harness
테스팅

이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.

스킬 보기
cloudflare-cron-triggers
테스팅

이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.

스킬 보기
webapp-testing
테스팅

이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.

스킬 보기
finishing-a-development-branch
테스팅

이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.

스킬 보기