Refactoring by Vibe: Code Better Without Writing Code
Refactoring là nghệ thuật cải thiện code quality mà không thay đổi functionality. Với AI, bạn có thể refactor like a senior engineer chỉ bằng cách describe code nên trông như thế nào.
Khi Nào Cần Refactoring?
Code Smells (Mùi Code Xấu):
- Functions quá dài (>50 lines)
- Deeply nested conditionals
- Duplicate logic across files
- Unclear variable names
- Mixed responsibilities in single file
- "Magic numbers" without explanation
Trigger Points:
- Trước khi add new feature
- Sau khi fix bug (consolidate learnings)
- Code review feedback
- Performance issues
- Preparing for team handoff
Refactoring Prompt Templates
1. Extract Function
@file components/ProductPage.tsx
Function `handleSubmit` (lines 45-120) quá dài.
Extract thành smaller functions:
- validateFormData(): FormData | ValidationError
- createProduct(): Promise<Product>
- handleSuccess(): void
- handleError(error: Error): void
Maintain current functionality, improve readability.
2. Remove Duplication
@file utils/api.ts
@file utils/fetch.ts
Hai files này có duplicate error handling logic.
Consolidate thành single utility:
- Shared error handler
- Consistent response format
- Reusable across both
Show diff của changes.
3. Improve Naming
@file services/data.ts
Improve variable và function names:
Current: const d = getData(); processD(d); setD(result);
Better: Descriptive names reflecting business logic
Explain reasoning cho mỗi rename.
4. Simplify Conditionals
@file components/UserStatus.tsx
Nested if-else (lines 23-45) khó đọc.
Refactor using:
- Early returns
- Guard clauses
- Hoặc lookup object pattern
Before: [paste current code section]
5. Type Safety
@file types/api.ts
@file utils/api.ts
Add strict typing:
- Replace "any" với proper types
- Add generics where appropriate
- Ensure null/undefined handled
No runtime behavior changes.
Advanced Refactoring Patterns
Component Composition:
@file components/Dashboard.tsx
Component này quá lớn (500+ lines).
Decompose thành:
- DashboardHeader
- DashboardMetrics
- DashboardCharts
- DashboardActions
Each component single responsibility.
Create barrel export index.ts.
Custom Hook Extraction:
@file components/Profile.tsx
Logic cho data fetching + state management mixed với UI.
Extract custom hook:
- useProfile(userId): handles fetch, cache, error states
- Component chỉ handle rendering
Follow existing hook patterns in @folder hooks/
API Layer Abstraction:
@folder app/api
@file lib/db.ts
API routes directly call database.
Create service layer:
- /services/productService.ts
- Handles business logic
- API routes become thin controllers
Pattern như @file services/userService.ts
Refactoring Safety Checklist
| Step | Action |
|---|---|
| 1 | Ensure tests exist (or write them first) |
| 2 | Make one refactoring at a time |
| 3 | Run tests after each change |
| 4 | Git commit frequently |
| 5 | Review diff before finalizing |
Pro Tips Cho Safe Refactoring
- Incremental changes: Một commit = một refactor
- Test coverage: Nếu không có tests, write tests FIRST
- Compare behavior: App phải work exactly same after refactor
- Document why: Comment lý do refactor for future devs
- Peer review: Ask AI to review the refactored code
🔥 Rule: Good refactoring = invisible to users, valuable to developers.
Measuring Improvement
Metrics để track:
- File length (LOC per file)
- Function complexity (cyclomatic complexity)
- Duplication percentage
- Type coverage
- Test coverage
"Analyze @file utils/helpers.ts
Report: LOC, number of functions, any types count,
complexity score. Suggest priority refactors."
Bài Tập
Pick một file trong project của bạn. Ask AI to:
- Identify top 3 code smells
- Prioritize refactoring order
- Implement most impactful refactor
- Explain improvement metrics
