跳到主要内容

refactor 精选

Refactor code có hệ thống dựa trên phương pháp luận của Martin Fowler. Sử dụng khi người dùng yêu cầu refactor code, cải thiện cấu trúc code, giảm nợ kỹ thuật, dọn code legacy, loại bỏ code smells, hoặc cải thiện khả năng duy trì code. Skill này hướng dẫn qua cách tiếp theo từng giai đoạn với nghiên cứu, lập kế hoạch, và triển khai tăng dần an toàn.

在 GitHub 打开

安装方式

cp -r vi/03-skills/refactor ~/.claude/skills/refactor-3

把该 skill 目录放进客户端 skills 目录。不同客户端的目录可能不同,Claude Code 默认是 ~/.claude/skills/

整仓一次性获取:git clone --depth 1 https://github.com/luongnv89/claude-howto.git

依赖与权限

  • 无需 API Key
  • 无需联网
  • 依赖外部命令:npm python
  • 以上为按正文与 frontmatter 自动推断的信号,仅供参考;安装前建议先阅读原文。

SKILL.md 正文

来源 luongnv89/claude-howto@065ab37 · 许可 MIT · 内容未修改

Code Refactoring Skill

Một cách tiếp có hệ thống để refactor code dựa trên Refactoring: Improving the Design of Existing Code (ấn bản 2) của Martin Fowler. Skill này nhấn mạnh các thay đổi tăng dần, an toàn được hỗ trợ bởi tests.

"Refactoring là quá trình thay đổi một hệ thống phần mềm theo cách mà nó không làm thay đổi hành vi bên ngoài của code nhưng cải thiện cấu trúc nội bộ của nó." — Martin Fowler

Nguyên Tắc Cốt Lõi

  1. Bảo Tồn Hành Vi: Hành vi bên ngoài phải không thay đổi
  2. Các Bước Nhỏ: Thực hiện các thay đổi nhỏ, có thể test
  3. Được Dẫn Bởi Test: Tests là lưới an toàn
  4. Liên Tục: Refactoring là liên tục, không phải sự kiện một lần
  5. Hợp Tác: Cần sự chấp thuận của người dùng tại mỗi giai đoạn

Tổng Quan Workflow

Giai Đoạn 1: Nghiên Cứu & Phân Tích
    ↓
Giai Đoạn 2: Đánh Giá Phủ Vùng Test
    ↓
Giai Đoạn 3: Xác Định Code Smell
    ↓
Giai Đoạn 4: Tạo Kế Hoạch Refactoring
    ↓
Giai Đoạn 5: Triển Khai Tăng Dần
    ↓
Giai Đoạn 6: Review & Lặp Lại

Giai Đoạn 1: Nghiên Cứu & Phân Tích

Mục Tiêu

  • Hiểu cấu trúc và mục đích của codebase
  • Xác định phạm vi của refactoring
  • Thu thập bối cảnh về các yêu cầu kinh doanh

Câu Hỏi Đặt Cho Người Dùng

Trước khi bắt đầu, làm rõ:

  1. Phạm Vi: Những file/module/hàm nào cần refactor?
  2. Mục Tiêu: Bạn đang cố gắng giải quyết vấn đề gì? (khả đọc, hiệu suất, khả năng duy trì)
  3. Ràng Buộc: Có những khu vực nào KHÔNG NÊN thay đổi không?
  4. Áp Lực Thời Gian: Điều này có chặn công việc khác không?
  5. Trạng Thái Test: Tests có tồn tại không? Chúng có pass không?

Hành Động

  • [ ] Đọc và hiểu code mục tiêu
  • [ ] Xác định dependencies và integrations
  • [ ] Tài liệu hóa kiến trúc hiện tại
  • [ ] Ghi chú bất kỳ markers nợ kỹ thuật hiện có (TODOs, FIXMEs)

Đầu Ra

Trình bày phát hiện cho người dùng:

  • Tóm tắt cấu trúc code
  • Các khu vực vấn đề được xác định
  • Khuyến nghị ban đầu
  • Yêu cầu chấp thuận để tiếp tục

Giai Đoạn 2: Đánh Giá Phủ Vùng Test

Tại Sao Tests Quan Trọng

"Refactoring mà không có tests giống như lái xe mà không có thắt dây an toàn." — Martin Fowler

Tests là bật dụng chính của refactoring an toàn. Không có chúng, bạn có nguy cơ giới thiệu bugs.

Các Bước Đánh Giá

  1. Kiểm tra các test hiện có
   # Tìm các file test
   find . -name "*test*" -o -name "*spec*" | head -20
  1. Chạy các test hiện có
   # JavaScript/TypeScript
   npm test

   # Python
   pytest -v

   # Java
   mvn test
  1. Kiểm tra phủ vùng (nếu có)
   # JavaScript
   npm run test:coverage

   # Python
   pytest --cov=.

Điểm Quyết Định: Hỏi Người Dùng

Nếu tests tồn tại và pass:

  • Tiếp tục đến Giai Đoạn 3

Nếu tests bị thiếu hoặc không hoàn chỉnh:

Trình bày các tùy chọn:

  1. Viết tests trước (khuyến nghị)
  2. Thêm tests tăng dần trong khi refactoring
  3. Tiếp tục mà không có tests (rủi ro - yêu cầu sự thừa nhận của người dùng)

Nếu tests đang fail:

  • DỪNG LẠI. Sửa các test fail trước khi refactoring
  • Hỏi người dùng: Chúng ta nên sửa tests trước không?

Hướng Dẫn Viết Test (nếu cần)

Đối với mỗi hàm được refactor, đảm bảo tests bao phủ:

  • Happy path (hoạt động bình thường)
  • Các trường hợp ngoại lệ (đầu vào trống, null, ranh giới)
  • Các kịch bản lỗi (đầu vào không hợp lệ, ngoại lệ)

Sử dụng chu trình "red-green-refactor":

  1. Viết test fail (red)
  2. Làm cho nó pass (green)
  3. Refactor

Giai Đoạn 3: Xác Định Code Smell

Code Smells Là Gì?

Các triệu chứng của các vấn đề sâu hơn trong code. Chúng không phải là bugs, nhưng là các chỉ báo rằng code có thể được cải thiện.

Các Code Smells Phổ Biến Để Kiểm Tra

Xem [references/code-smells.md](../../../03-skills/refactor/references/code-smells.md) để có danh sách đầy đủ.

Tham Khảo Nhanh

SmellDấu HiệuTác Động
Long MethodMethods > 30-50 dòngKhó hiểu, test, duy trì
Duplicated CodeCùng logic ở nhiều nơiCần sửa lỗi ở nhiều nơi
Large ClassClass với quá nhiều trách nhiệmVi phạm Single Responsibility
Feature EnvyMethod sử dụng dữ liệu class khác nhiềuĐóng gói kém
Primitive ObsessionLạm dụng primitives thay vì objectsThiếu các khái niệm domain
Long Parameter ListMethods với 4+ parametersKhó gọi đúng
Data ClumpsCùng dữ liệu xuất hiện cùng nhauThiếu abstraction
Switch StatementsSwitch/if-else chains phức tạpKhó mở rộng
Speculative GeneralityCode "trường hợp"Độ phức tạp không cần thiết
Dead CodeCode không sử dụngNhầm lẫn, gánh nặng duy trì

Các Bước Phân Tích

  1. Phân Tích Tự Động (nếu scripts có sẵn)
   python scripts/detect-smells.py <file>
  1. Review Thủ Công
  • Đi qua code một cách có hệ thống
  • Ghi chú mỗi smell với vị trí và mức độ nghiêm trọng
  • Phân loại theo tác động (Nguy Kịch/Cao/Trung Bình/Thấp)
  1. Ưu Tiên

Tập trung vào các smells mà:

  • Chặn phát triển hiện tại
  • Gây bugs hoặc nhầm lẫn
  • Ảnh hưởng đến các đường dẫn code được thay đổi nhiều nhất

Đầu Ra: Báo Cáo Smell

Trình bày cho người dùng:

  • Danh sách các smells được xác định với vị trí
  • Đánh giá mức độ nghiêm trọng cho mỗi smell
  • Thứ tự ưu tiên được khuyến nghị
  • Yêu cầu chấp thuận về các ưu tiên

Giai Đoạn 4: Tạo Kế Hoạch Refactoring

Chọn Refactorings

Đối với mỗi smell, chọn một refactoring phù hợp từ catalog.

Xem [references/refactoring-catalog.md](../../../03-skills/refactor/references/refactoring-catalog.md) để có danh sách đầy đủ.

Smell-to-Refactoring Mapping

Code SmellRefactoring Khuyến Nghị
Long MethodExtract Method, Replace Temp with Query
Duplicated CodeExtract Method, Pull Up Method, Form Template Method
Large ClassExtract Class, Extract Subclass
Feature EnvyMove Method, Move Field
Primitive ObsessionReplace Primitive with Object, Replace Type Code with Class
Long Parameter ListIntroduce Parameter Object, Preserve Whole Object
Data ClumpsExtract Class, Introduce Parameter Object
Switch StatementsReplace Conditional with Polymorphism
Speculative GeneralityCollapse Hierarchy, Inline Class, Remove Dead Code
Dead CodeRemove Dead Code

Cấu Trúc Kế Hoạch

Sử dụng mẫu tại [templates/refactoring-plan.md](../../../03-skills/refactor/templates/refactoring-plan.md).

Đối với mỗi refactoring:

  1. Mục Tiêu: Code nào sẽ thay đổi
  2. Smell: Vấn đề nào nó giải quyết
  3. Refactoring: Kỹ thuật nào để áp dụng
  4. Các Bước: Các micro-bước chi tiết
  5. Rủi Ro: Điều gì có thể sai
  6. Hoàn Tác: Cách hoàn tác nếu cần

Cách Tiếp Theo Giai Đoạn

QUAN TRỌNG: Introduce refactoring tăng dần theo các giai đoạn.

Giai Đoạn A: Quick Wins (Rủi ro thấp, giá trị cao)

  • Đổi tên biến để rõ hơn
  • Extract code trùng lặp rõ ràng
  • Loại bỏ dead code

Giai Đoạn B: Cải Tiến Cấu Trúc (Rủi ro trung bình)

  • Extract methods từ các hàm dài
  • Introduce parameter objects
  • Move methods đến các lớp phù hợp

Giai Đoạn C: Thay Đổi Kiến Trúc (Rủi ro cao hơn)

  • Thay thế conditionals với polymorphism
  • Extract classes
  • Introduce design patterns

Điểm Quyết Định: Trình Bày Kế Hoạch Cho Người Dùng

Trước khi triển khai:

  • Hiển thị kế hoạch refactoring hoàn chỉnh
  • Giải thích mỗi giai đoạn và rủi ro của nó
  • Nhận sự chấp thuận rõ ràng cho mỗi giai đoạn
  • Hỏi: "Tôi có nên tiếp tục với Giai Đoạn A không?"

Giai Đoạn 5: Triển Khai Tăng Dần

Quy Tắc Vàng

"Thay Đổi → Test → Xanh? → Commit → Bước tiếp theo"

Nhịp Triển Khai

Đối với mỗi bước refactoring:

  1. Kiểm tra trước
  • Tests đang pass (xanh)
  • Code biên dịch
  1. Thực hiện MỘT thay đổi nhỏ
  • Làm theo các cơ chế từ catalog
  • Giữ thay đổi tối thiểu
  1. Xác Minh
  • Chạy tests ngay lập tức
  • Kiểm tra lỗi biên dịch
  1. Nếu tests pass (xanh)
  • Commit với thông điệp mô tả
  • Di chuyển đến bước tiếp theo
  1. Nếu tests fail (đỏ)
  • DỪNG LẠI ngay lập tức
  • Hoàn tác thay đổi
  • Phân tích điều gì sai
  • Hỏi người dùng nếu không rõ

Chiến Lược Commit

Mỗi commit nên là:

  • Nguyên Tử: Một thay đổi logic
  • Có Thể Hoàn Tác: Dễ dàng revert
  • Mô Tả: Thông điệp commit rõ ràng

Ví dụ thông điệp commit:

refactor: Extract calculateTotal() from processOrder()
refactor: Rename 'x' to 'customerCount' for clarity
refactor: Remove unused validateOldFormat() method

Báo Cáo Tiến Độ

Sau mỗi sub-giai đoạn, báo cáo cho người dùng:

  • Các thay đổi được thực hiện
  • Tests vẫn pass?
  • Bất kỳ vấn đề nào gặp phải
  • Hỏi: "Tiếp tục với batch tiếp theo?"

Giai Đoạn 6: Review & Lặp Lại

Checklist Sau Refactoring

  • [ ] Tất cả tests pass
  • [ ] Không có cảnh báo/lỗi mới
  • [ ] Code biên dịch thành công
  • [ ] Hành vi không thay đổi (xác minh thủ công)
  • [ ] Tài liệu được cập nhật nếu cần
  • [ ] Lịch sử commit sạch

So Sánh Metrics

Chạy phân tích độ phức tạp trước và sau:

python scripts/analyze-complexity.py <file>

Trình bày cải tiến:

  • Thay đổi số dòng code
  • Thay đổi độ phức tạp vòng lục
  • Thay đổi chỉ số khả năng duy trì

Review Người Dùng

Trình bày kết quả cuối cùng:

  • Tóm tắt tất cả thay đổi
  • So sánh code trước/sau
  • Cải tiến metrics
  • Nợ kỹ thuật còn lại
  • Hỏi: "Bạn có hài lòng với những thay đổi này không?"

Các Bước Tiếp Theo

Thảo luận với người dùng:

  • Có smells bổ sung để giải quyết không?
  • Lên lịch refactoring tiếp theo?
  • Áp dụng các thay đổi tương tự ở nơi khác?

Hướng Dẫn Quan Trọng

Khi DỪNG LẠI và Hỏi

Luôn dừng lại và tham khảo người dùng khi:

  • Không chắc về logic kinh doanh
  • Thay đổi có thể ảnh hưởng APIs bên ngoài
  • Phủ vùng test không đủ
  • Cần quyết định kiến trúc quan trọng
  • Mức độ rủi ro tăng
  • Bạn gặp độ phức tạp bất ngờ

Quy Tắc An Toàn

  1. Không bao giờ refactor mà không có tests (trừ khi người dùng thừa nhận rủi ro một cách rõ ràng)
  2. Không bao giờ thực hiện các thay đổi lớn - chia thành các bước nhỏ
  3. Không bao giờ bỏ qua chạy test sau mỗi thay đổi
  4. Không bao giờ tiếp tục nếu tests fail - sửa hoặc hoàn tác trước
  5. Không bao giờ giả định - khi nghi ngờ, hãy hỏi

Những Gì KHÔNG Nên Làm

  • Đừng kết hợp refactoring với việc thêm tính năng
  • Đừng refactor trong các tình huống khẩn cấp của production
  • Đừng refactor code mà bạn không hiểu
  • Đừng over-engineer - giữ nó đơn giản
  • Đừng refactor tất cả cùng một lúc

Ví Dụ Bắt Đầu Nhanh

Kịch Bản: Long Method với Duplication

Trước:

function processOrder(order) {
  // 150 dòng code với:
  // - Logic xác thực trùng lặp
  // - Tính toán nội tuyến
  // - Trách nhiệm hỗn hợp
}

Các Bước Refactoring:

  1. Đảm bảo tests tồn tại cho processOrder()
  2. Extract xác thực vào validateOrder()
  3. Test - nên pass
  4. Extract tính toán vào calculateOrderTotal()
  5. Test - nên pass
  6. Extract thông báo vào notifyCustomer()
  7. Test - nên pass
  8. Review - processOrder() giờ điều phối 3 hàm rõ ràng

Sau:

function processOrder(order) {
  validateOrder(order);
  const total = calculateOrderTotal(order);
  notifyCustomer(order, total);
  return { order, total };
}

Tài Liệu Tham Khảo

  • [Catalog Code Smells](../../../03-skills/refactor/references/code-smells.md) - Danh sách đầy đủ code smells
  • [Catalog Refactoring](../../../03-skills/refactor/references/refactoring-catalog.md) - Các kỹ thuật refactoring
  • [Mẫu Kế Hoạch Refactoring](../../../03-skills/refactor/templates/refactoring-plan.md) - Mẫu lập kế hoạch

Scripts

  • scripts/analyze-complexity.py - Phân tích metrics độ phức tạp code
  • scripts/detect-smells.py - Phát hiện smell tự động

Lịch Sử Phiên Bản

  • v1.0.0 (2025-01-15): Phiên bản phát hành ban đầu với phương pháp luận Fowler, cách tiếp theo từng giai đoạn, các điểm tham khảo người dùng

质量与来源

所属仓库
luongnv89/claude-howto
仓库星标
4.2 万
最近更新
昨天
采集时间
今天
commit
065ab3734f64
内容指纹
sha256:ac71cf25ed854ad
文件路径
vi/03-skills/refactor/SKILL.md

同仓库其它 Skill

查看全部 25 个
lesson-quiz
Test a learner on a single Claude Code tutorial lesson (01-10) with 10 questions, scoring answers and flagging weak spots. Use before, during, or after a lesson. Don't use for whole-tutorial assessment or explaining a topic instead of testing it.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
self-assessment
Comprehensive Claude Code self-assessment and learning path advisor. Runs a multi-category quiz covering 10 feature areas, produces a detailed skill profile with per-topic scores, identifies specific gaps, and generates a personalized learning path with prioritized next steps. Use when asked to "assess my level", "take the quiz", "find my level", "where should I start", "what should I learn next", "check my skills", "skill check", or "level up".
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
blog-draft
Draft a blog post from ideas and resources. Use when users want to write a blog post, create content from research, or draft articles. Guides through research, brainstorming, outlining, and iterative drafting with version control.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
brand-voice
Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, public-facing content, or when users mention brand voice, tone, or writing style.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
claude-md
Create or update CLAUDE.md files following best practices for optimal AI agent onboarding
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端
code-review-specialist
Comprehensive code review with security, performance, and quality analysis. Use when users ask to review code, analyze code quality, evaluate pull requests, or mention code review, security analysis, or performance optimization.
精选 luongnv89/claude-howto 4.2 万 原文
Claude CodeMCP 客户端

相似 Skill

更多「写作」
interview-prep
Prepares the user for a specific interview from their real experience. Builds a story bank in Situation/Task/Action/Result/Reflection form mapped to the competencies the role and company test (such as Amazon's Leadership Principles), writes a cited company and role brief from public sources, predicts questions per round, drafts opener, why-us, weakness and salary answers, prepares questions to ask and a logistics checklist, and runs a post-interview debrief. Use when the user says "help me prepare for my interview", "I have an interview tomorrow" or "in 2 hours", "build my story bank", "STAR stories", "interviewing as a career changer", "what will they ask me", "how do I answer tell me about yourself", "questions to ask the interviewer", "research the company" or "debrief my interview". Uses Reactive Resume MCP tools when connected. For scored role-play practice, mock-interview; for thank-you notes and tracking, job-application-manager; for a salary number, offers or negotiation, offer-negotiation.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
job-application-manager
Runs the job-search pipeline. Adds jobs from a link or pasted posting, keeps stages and dates accurate, sets follow-ups, runs a weekly review (stale applications, next actions, funnel stats), records the exact resume version sent, and drafts networking, LinkedIn, referral, recruiter-reply, follow-up, thank-you, status-check, expedite and withdrawal messages without sending them. Use when the user says "add this job to my tracker", "I applied", "log my interview", "I got rejected", "I was ghosted", "log my offer", "track my applications", "do my weekly review", "what should I follow up on", "write a thank-you note", "message this recruiter", "ask for a referral", "withdraw my application", or wants a job-search spreadsheet. Works with a Markdown/CSV tracker or Reactive Resume MCP tools. Not for resume work (resume-tailor, resume-bullet-writer, resume-content-guide), interview prep or practice (interview-prep, mock-interview), or judging, negotiating, accepting or declining an offer (offer-negotiation).
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
mock-interview
Runs a mock interview for a specific job description. Plays the interviewer in a chosen round (recruiter screen, hiring manager, behavioral, coding, system design, case, product sense, panel), persona and difficulty; asks one question at a time, probes vague answers, and gives quote-backed rubric scores after each answer (coach mode) or at the end (realistic). Model answers use only the user's real experience. Use when the user says "mock interview me", "interview me for this job", "practice interview", "pretend you're the interviewer", "grill me for this role", "run a behavioral round", "quick recruiter screen", "hiring-manager mock", "system design mock" or "case interview practice". With Reactive Resume MCP it reads the application and stories and logs the session. For a story bank, company brief, questions to ask or a real-interview debrief, interview-prep; for scheduling or thank-you notes, job-application-manager; for fixing the resume, resume-tailor; for negotiation practice, offer-negotiation.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
offer-negotiation
Evaluates and negotiates job offers. Decodes base, bonus, equity, sign-on, level and terms with unknowns kept unknown and each offer in its own currency, benchmarks against checkable pay data, finds true leverage, drafts one counter as email and call script, role-plays the recruiter, and handles the salary-expectations number, deadlines and extensions, "best and final", competing offers, counteroffers and written acceptance or decline. Country-aware (India CTC, 13th-month pay, public-sector scales). Use when the user says "I got an offer of...", "is this offer good", "should I negotiate", "how do I counter", "compare my offers", "what is my equity worth", "they asked my salary expectations", "they want an answer by Friday", "can I ask for more time", "should I accept" or "practice the negotiation call". Uses Reactive Resume MCP tools when connected. For logging the offer, its deadline and withdrawal notes, job-application-manager; for other interview answers, interview-prep.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
resume-builder
Builds a complete resume from scratch as Reactive Resume JSON that conforms to the schema and imports at https://rxresu.me. Asks for each missing detail instead of inventing it, then produces valid JSON (UUIDs, HTML descriptions, template and layout). Use when the user wants to create, build or generate a new resume, turn their work history into Reactive Resume JSON, or asks about the Reactive Resume schema, sections, templates or layout. For what belongs on a resume or a resume audit use resume-content-guide; for rewriting bullets, resume-bullet-writer; for fitting one job posting, resume-tailor; for tracking applications, job-application-manager; for interviews, interview-prep or mock-interview.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI
resume-bullet-writer
Turns resume duties into truthful impact bullets. Questions the user role by role to dig out achievements, asks for real numbers or honest ranges (never invents them), and writes concise bullets in XYZ, CAR, scope or qualitative form. Use when the user says "rewrite my bullets", "make this bullet stronger", "quantify my resume", "turn my duties into achievements", "improve my experience section", "my resume sounds boring", "I don't have any numbers", pastes resume lines for feedback, or works in a low-number job (nursing, teaching, care, trades, admin, creative). With the Reactive Resume MCP server connected, it edits experience, project, volunteer and education descriptions with apply_resume_patch after the user approves. Use resume-content-guide instead for which sections or details belong and for summaries or headlines, resume-tailor to fit one job posting, interview-prep or mock-interview for interview stories and practice, and resume-builder to build a resume from scratch.
精选 reactive-resume/reactive-resume 4.4 万 原文
Claude CodeCodex CLIGemini CLI