* feat(i18n): add Vietnamese localization infrastructure Add comprehensive infrastructure for Vietnamese translation of the claude-howto documentation: Features: - Parallel vi/ directory structure for Vietnamese content - Modified build_epub.py with --lang flag for Vietnamese EPUB - Vietnamese-specific pre-commit hooks for quality checks - Translation support files (glossary, style guide, queue tracker) - sync_translations.py script to detect outdated translations Infrastructure: - vi/ directory with all 10 module subdirectories - TRANSLATION_NOTES.md: comprehensive glossary and style guide - TRANSLATION_QUEUE.md: progress tracking for 66+ files - vi/README.md: Vietnamese landing page EPUB Build: - Added --lang CLI flag (en/vi) to build_epub.py - Language-specific metadata (title, subtitle) - Automatic root path adjustment for vi/ directory - Dynamic output filename (claude-howto-guide-vi.epub) Quality Assurance: - Vietnamese markdown linting - Vietnamese cross-reference checking - Vietnamese Mermaid syntax validation - Vietnamese link checking - Vietnamese EPUB build validation Ready for translation work to begin. * feat(vi): translate INDEX.md to Vietnamese Complete Vietnamese translation of INDEX.md - the comprehensive index of all example files in the repository. Translation follows vi/TRANSLATION_NOTES.md guidelines: - Technical terms kept per glossary (slash command → "lệnh slash") - File paths and code blocks preserved in English - Table structure and formatting maintained - All 882 lines translated Content includes: - Complete file tree (10 modules, 100+ files) - Feature coverage matrix - Quick start guides by use case - Learning path progression - Search by keyword sections Progress: 1/5 core documents completed * feat(vi): translate CATALOG.md to Vietnamese Complete Vietnamese translation of CATALOG.md - the quick reference guide to all Claude Code features. Translation follows vi/TRANSLATION_NOTES.md guidelines: - Technical terms kept per glossary (slash command → "lệnh slash") - All command names preserved (/help, /optimize, etc.) - Code blocks, JSON examples, and bash commands unchanged - All tables and formatting maintained - 517 lines translated with complete feature coverage Content includes: - Summary statistics (99 built-in + 43 examples = 117 total) - Complete built-in commands reference (55+ commands) - Custom commands examples (8 commands) - Permission modes (6 modes) - Subagents (6 built-in + 10 custom) - Skills (5 bundled + 4 custom) - Plugins (3 complete plugins) - MCP servers (1 built-in + 8 common servers) - Hooks (25 events + 7 example hooks) - Memory files (7 types) - New features (March 2026) - 17 new features - Installation priority guide - Complete one-command installation Progress: 2/5 core documents completed * docs(vi): translate learning roadmap to Vietnamese - Add complete Vietnamese translation of LEARNING-ROADMAP.md (747 lines) - Include self-assessment quiz for level determination - Translate three learning levels: Beginner, Intermediate, Advanced - Translate all milestones (1A, 1B, 2A, 2B, 3A, 3B) with hands-on exercises - Preserve Mermaid diagram for learning path visualization - Maintain progress tracking checklists and learning tips * docs(vi): translate quick reference guide to Vietnamese - Add complete Vietnamese translation of QUICK_REFERENCE.md (507 lines) - Include installation quick commands for all features - Translate feature cheat sheet with usage examples - Translate common use cases (code review, documentation, DevOps, etc.) - Preserve all code snippets, commands, and file paths in English - Maintain file locations reference diagram - Include learning path and new features (March 2026) sections - Keep tips & tricks, feature matrix, and checklist intact * docs(vi): translate module 01 - slash commands to Vietnamese - Add complete Vietnamese translation of 01-slash-commands/README.md (553 lines) - Translate slash commands overview and architecture - Include 55+ built-in commands reference table with Vietnamese descriptions - Translate bundled skills section (5 skills) - Document custom commands (now skills) migration path - Include frontmatter reference, arguments, and dynamic context sections - Preserve all command names, code examples, and Mermaid diagrams - Translate 8 available commands in folder with usage examples - Include installation, troubleshooting, and best practices sections * docs(vi): update translation queue progress - Module 01 README done - Mark 01-slash-commands/README.md as completed (2026-04-02) - Update Module 01 progress: 1/9 files (11%) - Update overall progress: 6/66 files (9%) - Update Priority 2 progress: 1/31 files (3%) - Add recent completion note to queue header * docs(vi): translate slash command - commit to Vietnamese - Translate commit.md slash command to Vietnamese - Keep all git commands and technical syntax intact - Translate instructions and descriptions - Maintain conventional commits format documentation * docs(vi): translate slash command - doc-refactor to Vietnamese - Translate doc-refactor.md slash command to Vietnamese - Keep all technical terms and file paths intact - Translate documentation refactoring instructions - Maintain structure and numbering * docs(vi): translate slash command - generate-api-docs to Vietnamese - Translate generate-api-docs.md slash command to Vietnamese - Keep all technical terms and file paths intact - Translate API documentation generation instructions - Maintain output format specifications * docs(vi): translate slash command - optimize to Vietnamese - Translate optimize.md slash command to Vietnamese - Keep all technical terms and code concepts intact - Translate code optimization instructions - Maintain issue priority and response format * docs(vi): translate slash command - pr to Vietnamese - Translate pr.md slash command to Vietnamese - Keep all commands and technical syntax intact - Translate PR preparation checklist instructions - Maintain conventional commits format documentation * docs(vi): translate slash command - push-all to Vietnamese - Translate push-all.md slash command to Vietnamese (153 lines) - Keep all git commands and technical syntax intact - Translate comprehensive workflow with safety checks - Maintain API key validation patterns and error handling - Preserve when to use/avoid sections and alternatives * docs(vi): translate slash command - setup-ci-cd to Vietnamese - Translate setup-ci-cd.md slash command to Vietnamese - Keep all tool names and technical terms intact - Translate CI/CD pipeline implementation instructions - Maintain pre-commit hooks and GitHub Actions sections * docs(vi): translate slash command - unit-test-expand to Vietnamese - Translate unit-test-expand.md slash command to Vietnamese - Keep all framework names and technical terms intact - Translate test coverage expansion instructions - Maintain testing frameworks and scenario sections * docs(vi): update translation queue - Module 01 complete (100%) - Mark all 9 Module 01 files as completed (2026-04-02) - Update Module 01 progress: 9/9 files (100%) ✅ - Update overall progress: 14/66 files (21%) - Update Priority 2 progress: 9/31 files (29%) - Update header with Module 01 completion milestone Module 01: Slash Commands - All files translated: ✅ README.md (overview, built-in commands, skills) ✅ commit.md (git commit with context) ✅ doc-refactor.md (documentation restructuring) ✅ generate-api-docs.md (API documentation generator) ✅ optimize.md (code optimization analysis) ✅ pr.md (pull request preparation) ✅ push-all.md (stage, commit, push with safety) ✅ setup-ci-cd.md (CI/CD pipeline implementation) ✅ unit-test-expand.md (test coverage expansion) * docs(vi): translate module 02 - memory guide to Vietnamese - Add complete Vietnamese translation of 02-memory/README.md (1162 lines) - Translate memory system overview and architecture - Include quick reference for memory commands (/init, /memory, #) - Document complete memory hierarchy (8 levels with precedence) - Translate auto memory section with architecture diagrams - Include practical examples (project, directory-specific, personal memory) - Add best practices, installation instructions, and troubleshooting - Preserve all code examples, file paths, and technical terms - Maintain Mermaid diagrams and tables * docs(vi): translate example project CLAUDE.md to Vietnamese - Translate project-CLAUDE.md example memory file - Keep all technical terms, commands, and code style intact - Translate descriptions and explanations - Maintain project configuration structure * docs(vi): translate example personal CLAUDE.md to Vietnamese - Translate personal-CLAUDE.md example memory file - Keep all technical terms, tools, and preferences intact - Translate descriptions and explanations - Maintain personal preferences structure * docs(vi): translate example directory-specific CLAUDE.md to Vietnamese - Translate directory-api-CLAUDE.md example memory file - Keep all technical terms, API standards, and code examples intact - Translate descriptions and explanations - Maintain API module standards structure * docs(vi): update translation queue - Module 02 complete (100%) - Mark all 4 Module 02 files as completed (2026-04-02) - Update Module 02 progress: 4/4 files (100%) ✅ - Update overall progress: 18/66 files (27%) - Update Priority 2 progress: 13/31 files (42%) - Update header with Module 02 completion milestone Module 02: Memory - All files translated: ✅ README.md (1162 lines - comprehensive memory guide) ✅ project-CLAUDE.md (example project memory) ✅ personal-CLAUDE.md (example personal preferences) ✅ directory-api-CLAUDE.md (example directory-specific rules) * docs(vi): translate module 03 - skills guide to Vietnamese - Add complete Vietnamese translation of 03-skills/README.md (805 lines) - Translate Agent Skills overview and architecture - Include progressive disclosure loading mechanism (3 levels) - Document skill types, locations, and automatic discovery - Translate skill creation process and SKILL.md format - Include required and optional frontmatter fields - Document skill content types (reference vs task) - Translate controlling skill invocation and string substitutions - Include dynamic context injection with shell commands - Document running skills in subagents with context: fork - Translate 6 practical examples with directory structures - Add supporting files, management, and best practices sections - Preserve all code examples, YAML frontmatter, and Mermaid diagrams - Maintain tables, troubleshooting guides, and security considerations * docs(vi): translate skill - blog-draft to Vietnamese - Translate blog-draft/SKILL.md to Vietnamese (275 lines) - Keep all workflow steps and technical structure intact - Translate instructions and descriptions - Maintain version tracking and file structure - Preserve all markdown formatting and code examples * docs(vi): translate skill - brand-voice to Vietnamese - Translate brand-voice/SKILL.md to Vietnamese (73 lines) - Keep brand identity, tone, and vocabulary intact - Translate writing guidelines and examples - Maintain preferred/avoided terms sections - Preserve good/bad examples with explanations * docs(vi): translate skill - claude-md to Vietnamese - Translate claude-md/SKILL.md to Vietnamese (213 lines) - Keep all golden rules and core principles intact - Translate execution flow and content strategy - Maintain WHAT/WHY/HOW structure - Preserve quality constraints and validation checklist - Keep anti-patterns and output format sections * docs(vi): translate skill - code-review to Vietnamese - Translate code-review/SKILL.md to Vietnamese (71 lines) - Keep all review categories and template intact - Translate security, performance, quality, maintainability sections - Maintain review template structure - Preserve version history * docs(vi): translate skill - refactor to Vietnamese - Translate refactor/SKILL.md to Vietnamese (427 lines) - Keep all Martin Fowler refactoring methodology intact - Translate 6-phase workflow with detailed steps - Maintain core principles and safety rules - Preserve code smell catalog and refactoring techniques - Keep quick start example with before/after code - Maintain version history and references sections * docs(vi): update translation queue - Module 03 complete (100%) - Mark all 6 Module 03 files as completed (2026-04-02) - Update Module 03 progress: 6/6 files (100%) ✅ - Update overall progress: 24/66 files (36%) - Update Priority 2 progress: 19/31 files (61%) - Update header with Module 03 completion milestone Module 03: Skills - All files translated: ✅ README.md (805 lines - comprehensive skills guide) ✅ blog-draft/SKILL.md (275 lines - blog post creation workflow) ✅ brand-voice/SKILL.md (73 lines - brand voice consistency) ✅ claude-md/SKILL.md (213 lines - CLAUDE.md best practices) ✅ code-review/SKILL.md (71 lines - comprehensive code review) ✅ refactor/SKILL.md (427 lines - Fowler refactoring methodology) * docs(vi): translate Module 04 Subagents README Complete Vietnamese translation of subagents reference guide: - Configuration and built-in subagents (general-purpose, Plan, Explore, Bash, statusline-setup, Claude Code Guide) - Agent management with /agents command - Automatic delegation vs explicit invocation - Resumable agents and chaining - Persistent memory across agent sessions - Background subagents for parallel work - Worktree isolation for safe experimentation - Agent Teams (experimental feature) - Best practices and usage patterns * docs(vi): complete Module 04 Subagents translation Translate all 6 subagent example definitions: - code-reviewer.md: Expert code review specialist - debugger.md: Root cause analysis and debugging - documentation-writer.md: Technical documentation creation - implementation-agent.md: Full-stack feature implementation - secure-reviewer.md: Security-focused code review - test-engineer.md: Comprehensive test coverage Update translation queue progress: - Module 04: 7/7 files (100%) ✅ - Overall: 31/66 files (47%) - Next: Module 05 (MCP) * docs(vi): complete Module 05 MCP translation Translate comprehensive MCP (Model Context Protocol) guide: - Overview and architecture diagrams - Installation methods (HTTP, Stdio, SSE, WebSocket) - OAuth 2.0 authentication support - MCP tool search and dynamic updates - Elicitation and prompt slash commands - Configuration management (local, project, user scopes) - Practical examples (GitHub, Database, Filesystem, Slack MCPs) - MCP vs Memory decision matrix - Code execution approach for solving context bloat - MCPorter runtime reference - Security best practices and troubleshooting Translate 4 MCP configuration JSON examples: - filesystem-mcp.json: File operations - github-mcp.json: GitHub integration - database-mcp.json: SQL queries - multi-mcp.json: Multiple servers configuration Update translation queue progress: - Module 05: 5/5 files (100%) ✅ - Overall: 36/66 files (55%) - Next: Module 06 (Hooks) * docs(vi): complete Module 06 Hooks translation Translate comprehensive Hooks guide: - Overview and architecture - Configuration structure (user, project, local scopes) - Four hook types: command, HTTP, prompt, agent - 25 hook events with matcher patterns - Component-scoped hooks and subagent frontmatter - JSON input/output format and exit codes - Environment variables and best practices - Security considerations and debugging - Installation instructions Copy 9 hook example files (code, no translation needed): - format-code.sh: Auto-format code after write/edit - log-bash.sh: Bash command logging - notify-team.sh: Team notifications - pre-commit.sh: Pre-commit validation - security-scan.sh: Security scanning - validate-prompt.sh: Prompt validation - context-tracker.py: Token usage tracking - context-tracker-tiktoken.py: Accurate token counting Update translation queue progress: - Module 06: 9/9 files (100%) ✅ - Overall: 45/67 files (67%) - Next: Module 07 (Plugins) * docs(vi): complete Module 07 Plugins translation Translate comprehensive Plugins guide: - Overview and architecture diagrams - Plugin loading process and lifecycle - Plugin types (Official, Community, Organization, Personal) - Plugin definition structure and manifest - Plugin structure example with all directories - LSP server configuration and examples - Plugin options (v2.1.83+) with userConfig - Persistent plugin data via CLAUDE_PLUGIN_DATA - Inline plugins via settings (v2.1.80+) - Standalone vs Plugin approach comparison - Practical examples (PR Review, DevOps, Documentation plugins) - Plugin marketplace and distribution - Marketplace configuration and definition schema - Plugin source types and distribution methods - Plugin CLI commands and installation methods - Plugin features comparison table - Testing, hot-reload, and managed settings - Plugin security restrictions - Publishing workflow and best practices - Complete troubleshooting guide Copy all plugin subdirectories (code, no translation needed): - devops-automation/: Deployment workflows, incident management - documentation/: API docs, README generation, templates - pr-review/: Pull request review automation Update translation queue progress: - Module 07: 10+/10+ files (100%) ✅ - Overall: 55+/67 files (82%) - Next: Module 08-10 (Checkpoints, Advanced Features, CLI) * docs(vi): complete Modules 08-10 translation Module 08: Checkpoints and Rewind (2 files) - Overview and architecture - Access methods (keyboard shortcut, slash command) - Five rewind options (restore code+conversation, conversation, code, summarize, cancel) - Automatic checkpoints and retention policies - Use cases and practical examples - Integration with git and best practices Module 09: Advanced Features (3 files) - Planning Mode: Two-phase implementation approach - Extended Thinking: Deep reasoning for complex problems - Auto Mode: Background safety classifier - Background Tasks, Scheduled Tasks - Permission Modes (default, acceptEdits, plan, auto, dontAsk, bypassPermissions) - Print Mode, Session Management - Voice Dictation, Channels, Remote Control - Web Sessions, Desktop App, Task List - Git Worktrees, Sandboxing, Managed Settings Module 10: CLI Reference (1 file) - CLI commands reference - Core flags and options - Interactive vs Print Mode - Model selection and configuration - System prompt customization - Tool & permission management - Output formats and scripting Update translation queue progress: - Modules 08-10: 6/6 files (100%) ✅ - All Modules 01-10: 61+/61+ files (100%) ✅ - Overall: 61+/67 files (91%) - Remaining: Supporting docs (6 files) * docs(vi): complete supporting documentation translation Translate all 5 supporting documents: - CONTRIBUTING.md: Contribution guidelines - SECURITY.md: Security policy and vulnerability reporting - CODE_OF_CONDUCT.md: Community standards and harassment policy - STYLE_GUIDE.md: Documentation formatting conventions - CHANGELOG.md: Version history (v2.2.0, v2.1.1, v2.1.0, v2.0.0) Update translation queue to 100% completion: - All Modules 01-10: 61+ files (100%) ✅ - Supporting Docs: 5/5 files (100%) ✅ - Overall: 67+/67 files (100%) ✅ - Status: HOÀN THÀNH ✅ * fix(vi): fix mermaid syntax and broken cross-references in Vietnamese translation Fix invalid `#` comment in mermaid block (use `%%` instead) and update cross-reference script to support Unicode/Vietnamese diacritics in anchor generation. Fix broken anchor links across vi/ documentation files. * fix(vi): remove inline mermaid comment causing parse error Inline %% comments on node definition lines are not supported by the mermaid parser. The surrounding HTML comment already explains this is an incorrect example.
14 KiB
name, description
| name | description |
|---|---|
| code-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. |
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
- Bảo Tồn Hành Vi: Hành vi bên ngoài phải không thay đổi
- Các Bước Nhỏ: Thực hiện các thay đổi nhỏ, có thể test
- Được Dẫn Bởi Test: Tests là lưới an toàn
- Liên Tục: Refactoring là liên tục, không phải sự kiện một lần
- 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õ:
- Phạm Vi: Những file/module/hàm nào cần refactor?
- 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ì)
- Ràng Buộc: Có những khu vực nào KHÔNG NÊN thay đổi không?
- Áp Lực Thời Gian: Điều này có chặn công việc khác không?
- 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á
-
Kiểm tra các test hiện có
# Tìm các file test find . -name "*test*" -o -name "*spec*" | head -20 -
Chạy các test hiện có
# JavaScript/TypeScript npm test # Python pytest -v # Java mvn test -
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:
- Viết tests trước (khuyến nghị)
- Thêm tests tăng dần trong khi refactoring
- 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":
- Viết test fail (red)
- Làm cho nó pass (green)
- 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 để có danh sách đầy đủ.
Tham Khảo Nhanh
| Smell | Dấu Hiệu | Tác Động |
|---|---|---|
| Long Method | Methods > 30-50 dòng | Khó hiểu, test, duy trì |
| Duplicated Code | Cùng logic ở nhiều nơi | Cần sửa lỗi ở nhiều nơi |
| Large Class | Class với quá nhiều trách nhiệm | Vi phạm Single Responsibility |
| Feature Envy | Method sử dụng dữ liệu class khác nhiều | Đóng gói kém |
| Primitive Obsession | Lạm dụng primitives thay vì objects | Thiếu các khái niệm domain |
| Long Parameter List | Methods với 4+ parameters | Khó gọi đúng |
| Data Clumps | Cùng dữ liệu xuất hiện cùng nhau | Thiếu abstraction |
| Switch Statements | Switch/if-else chains phức tạp | Khó mở rộng |
| Speculative Generality | Code "trường hợp" | Độ phức tạp không cần thiết |
| Dead Code | Code không sử dụng | Nhầm lẫn, gánh nặng duy trì |
Các Bước Phân Tích
-
Phân Tích Tự Động (nếu scripts có sẵn)
python scripts/detect-smells.py <file> -
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)
-
Ư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 để có danh sách đầy đủ.
Smell-to-Refactoring Mapping
| Code Smell | Refactoring Khuyến Nghị |
|---|---|
| Long Method | Extract Method, Replace Temp with Query |
| Duplicated Code | Extract Method, Pull Up Method, Form Template Method |
| Large Class | Extract Class, Extract Subclass |
| Feature Envy | Move Method, Move Field |
| Primitive Obsession | Replace Primitive with Object, Replace Type Code with Class |
| Long Parameter List | Introduce Parameter Object, Preserve Whole Object |
| Data Clumps | Extract Class, Introduce Parameter Object |
| Switch Statements | Replace Conditional with Polymorphism |
| Speculative Generality | Collapse Hierarchy, Inline Class, Remove Dead Code |
| Dead Code | Remove Dead Code |
Cấu Trúc Kế Hoạch
Sử dụng mẫu tại templates/refactoring-plan.md.
Đối với mỗi refactoring:
- Mục Tiêu: Code nào sẽ thay đổi
- Smell: Vấn đề nào nó giải quyết
- Refactoring: Kỹ thuật nào để áp dụng
- Các Bước: Các micro-bước chi tiết
- Rủi Ro: Điều gì có thể sai
- 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:
-
Kiểm tra trước
- Tests đang pass (xanh)
- Code biên dịch
-
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
-
Xác Minh
- Chạy tests ngay lập tức
- Kiểm tra lỗi biên dịch
-
Nếu tests pass (xanh)
- Commit với thông điệp mô tả
- Di chuyển đến bước tiếp theo
-
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
- 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)
- Không bao giờ thực hiện các thay đổi lớn - chia thành các bước nhỏ
- Không bao giờ bỏ qua chạy test sau mỗi thay đổi
- Không bao giờ tiếp tục nếu tests fail - sửa hoặc hoàn tác trước
- 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:
- Đảm bảo tests tồn tại cho processOrder()
- Extract xác thực vào validateOrder()
- Test - nên pass
- Extract tính toán vào calculateOrderTotal()
- Test - nên pass
- Extract thông báo vào notifyCustomer()
- Test - nên pass
- 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 - Danh sách đầy đủ code smells
- Catalog Refactoring - Các kỹ thuật refactoring
- Mẫu Kế Hoạch Refactoring - Mẫu lập kế hoạch
Scripts
scripts/analyze-complexity.py- Phân tích metrics độ phức tạp codescripts/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