Chuyển đến nội dung chính

Bài 17: Code Quality & Review — Vibe Coding có trách nhiệm

Đảm bảo chất lượng code khi dùng Vibe Coding. Code review AI-generated code. Linting, formatting, type safety. Metrics và KPIs. Anti-patterns cần tránh. Best practices cho code quality trong Vibe Coding workflow.

💻 Lập trình — Bài 17 Bài 17: Code Quality & Review — Vibe Coding có trách nhiệm

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 6: Vibe Coding chuyên nghiệp — Quality, Security & Production

xdev.asia

1. Vấn đề chất lượng trong Vibe Coding

Andrej Karpathy khi giới thiệu Vibe Coding đã nói: "I just see things, say things, run things, and copy-paste things, and it mostly works." Nhưng "mostly works" không đủ cho production code.

Dữ liệu thực tế (2025-2026):

Nguồn Phát hiện
GitClear (2025) "Code churn" tăng sau khi áp dụng AI — code viết ra rồi sửa/xóa nhiều hơn
VeraCode (2026) 72% ứng dụng dùng AI-generated code có ít nhất 1 lỗ hổng bảo mật
CodeRabbit (2026) AI code review phát hiện bugs mà human reviewers bỏ sót

2. Cách Review AI-Generated Code

2.1. Checklist review cho AI code

  • ✅ Logic correctness: Code có làm đúng yêu cầu không?
  • ✅ Edge cases: AI thường bỏ sót null, empty, boundary cases
  • ✅ Error handling: Có catch errors phù hợp không?
  • ✅ Security: Input validation, auth checks, SQL injection
  • ✅ Performance: N+1 queries, unnecessary re-renders
  • ✅ Naming: Variables, functions có ý nghĩa không?
  • ✅ Duplication: AI thường generate thay vì reuse code có sẵn

2.2. Dùng Copilot để review chính code của nó

// Prompt:
Review this code for:
1. Security vulnerabilities
2. Performance issues
3. Edge cases not handled
4. Code that doesn't follow our project conventions
5. Potential bugs

Be critical and thorough. List every issue found.

2.3. Anti-patterns phổ biến trong AI code

Anti-pattern Ví dụ Fix
God function Một hàm 200 dòng làm mọi thứ Split thành smaller functions
Copy-paste code Lặp lại logic thay vì extract Extract shared utilities
Hardcoded values Magic numbers, URLs trong code Move to config/env
Weak error handling Silent catch hoặc generic errors Specific error handling
Missing validation Trust user input hoàn toàn Validate at boundaries
Over-engineering Abstract quá sớm, factory pattern cho 1 case YAGNI — chỉ build khi cần

3. Automated Quality Gates

3.1. ESLint + Prettier + Copilot Hooks

// .vscode/settings.json
{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "github.copilot.chat.hooks": {
    "postSave": [
      {
        "command": "npx eslint --fix ${file}",
        "pattern": "**/*.{ts,tsx}"
      }
    ]
  }
}

3.2. Pre-commit hooks

// package.json
{
  "lint-staged": {
    "*.{ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "pre-push": "npm test"
    }
  }
}

3.3. CI/CD quality checks

# .github/workflows/quality.yml
name: Code Quality
on: [pull_request]
jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm ci
      - run: npx tsc --noEmit          # Type check
      - run: npx eslint .              # Lint
      - run: npm test -- --coverage    # Tests + coverage
      - run: npx knip                  # Dead code detection

4. Type Safety — Tuyến phòng thủ đầu tiên

TypeScript strict mode bắt nhiều bugs mà AI tạo ra:

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitReturns": true,
    "exactOptionalPropertyTypes": true
  }
}
// Prompt mẫu yêu cầu type safety:
Ensure all functions have explicit return types.
Use discriminated unions for API responses.
No 'any' types — use 'unknown' with type guards instead.

5. Test Coverage Strategy

AI code cần test nhiều hơn, không phải ít hơn:

// Prompt:
Write tests for the TaskService focusing on:
1. Happy path for each method
2. Edge cases: empty input, null values, max length
3. Authorization: user can only access own projects
4. Concurrent modifications
5. Database constraint violations

Minimum coverage targets:

Layer Target Lý do
Business logic 90%+ Core domain cần chính xác
API endpoints 80%+ Integration tests cho contracts
UI components 70%+ Interaction tests cho UX
Utilities 95%+ Pure functions dễ test

6. Metrics & KPIs cho Vibe Coding

Metric Đo gì Target
Acceptance rate % AI suggestions được accept 30-40% (quá cao = không review)
Code churn % code sửa/xóa trong 2 tuần <25%
Bug density Bugs per 1000 LOC Giảm hoặc giữ nguyên so với trước AI
Review comments Số lần reviewer yêu cầu sửa AI code Giảm theo thời gian
Time to PR merge Thời gian từ tạo PR đến merge Giảm nhưng không vì skip review

7. Best Practices tổng hợp

  1. Không accept blindly: Đọc TỪNG dòng AI generate
  2. Yêu cầu AI giải thích: "Explain why you chose this approach"
  3. Test-first khi có thể: Viết test trước, dùng AI implement
  4. Incremental generation: Generate từng phần nhỏ, review xong mới tiếp
  5. Custom instructions: Enforce coding standards qua copilot-instructions.md
  6. Automated gates: CI/CD bắt bugs mà human review bỏ sót
  7. Measure quality: Track metrics để biết AI đang giúp hay hại

8. Tổng kết

Vibe Coding có trách nhiệm = tận dụng tốc độ của AI + giữ chất lượng của human engineering.

Code AI sinh ra cần được review kỹ hơn code con người viết, vì:

  • AI không hiểu business context
  • AI ưu tiên code "trông đúng" hơn code "chạy đúng"
  • AI không biết code hiện tại trong project đã có sẵn gì

Bài tiếp theo: Security trong Vibe Coding — những lỗ hổng bảo mật phổ biến và cách phòng tránh.