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

第 19 課:技術債與可維護性

使用 Vibe Coding 時管理技術債。 GitClear 有關程式碼變更的資料。重構策略。死代碼檢測。文檔生成。架構決策。長期可維護性。

💻 程式設計 — 第 19 課 第 19 課:技術債與可維護性

使用 GitHub Copilot 進行 Vibe 編碼:從基礎知識到高級

第 6 部分:專業 Vibe 編碼 — 品質、安全與生產

亞洲開發網

1. Vibe 編碼和技術債務

Vibe Coding 可以加快程式碼編寫速度,但如果不小心就會創建 技術債 比以往任何時候都快。

來自 GitClear 的數據(2025):

公制 人工智慧出現之前(2022) 下一個人工智慧 (2025) 改變
程式碼流失 3.3% 7.1% +115%
新增的行數/開發/月 1,100 1,800 +64%
刪除行數/dev/月 200 550 +175%
移動/複製的程式碼 5% 11% +120%

程式碼流失 = 寫下程式碼,然後在 2 週內編輯或刪除它。翻倍的數字顯示 AI從一開始就創建了錯誤的程式碼。

2. Vibe Coding 技術債的原因

2.1.重複-重複的程式碼

AI 產生新程式碼而不是重複使用:

// AI tạo helper function mới
function formatDate(date: Date): string {
  return date.toLocaleDateString('vi-VN');
}

// Mặc dù project đã có: // src/utils/date.ts → formatDate()

2.2.不一致——不一致

// File A: AI dùng async/await
const data = await fetchUsers();

// File B: AI dùng .then() fetchUsers().then(data => { ... });

// File C: AI dùng callback fetchUsers((err, data) => { ... });

2.3.過度抽象化-複雜化

// AI hay tạo Factory + Strategy + Builder cho task đơn giản:
class TaskBuilderFactory {
  createBuilder(type: string): TaskBuilder {
    // 50 lines of over-engineering
  }
}

// Thực tế chỉ cần: function createTask(data: CreateTaskInput): Task { return prisma.task.create({ data }); }

3. 檢測技術債

3.1.死代碼檢測

// Dùng knip để tìm dead code:
npx knip

// Output: Unused files: src/utils/old-helper.ts Unused exports: TaskBuilderFactory (src/builders/task.ts) Unused dependencies: moment, lodash

3.2.重複檢測

// Dùng jscpd:
npx jscpd src/

// Output: Found 12 clones across 8 files Total duplicated lines: 156 (8.3% of total)

3.3.複雜性分析

// Dùng Copilot để phân tích:
@workspace Analyze cyclomatic complexity of all functions.
List functions with complexity > 10 and suggest refactoring.

4. 人工智慧重構

4.1.提取重複項

// Prompt:
I have similar date formatting logic in 5 files.
Extract into a shared utility module.
Show me which files to update and what to extract.

4.2.簡化複雜功能

// Prompt:
This function has 15 if-else branches.
Refactor using:
- Strategy pattern for different task types
- Early returns to reduce nesting
- Extract validation into separate function
Keep the same behavior, add tests to verify.

4.3.標準化模式

// Prompt:
Our codebase has inconsistent error handling:
- Some files use try/catch
- Some use .catch()
- Some don't handle errors at all

Standardize all API calls to use async/await with a shared error handler middleware. Show me the changes needed file by file.

5. 利用人工智慧產生文檔

// Prompt cho API documentation:
Generate OpenAPI 3.0 spec for all endpoints in src/routes/.
Include request/response schemas, auth requirements,
and example values.

// Prompt cho code documentation:
Add JSDoc comments to all exported functions in src/services/.
Include parameter descriptions, return types, and usage examples.
Explain the business logic, not just the code.

架構決策記錄 (ADR)

// Prompt:
Create an ADR for our decision to use Prisma ORM with PostgreSQL.
Include:
- Context: why we needed an ORM
- Options considered: Prisma, TypeORM, Knex, Drizzle
- Decision and rationale
- Consequences and trade-offs
Follow the format in docs/adr/template.md

6. 防止技術債

6.1.定制說明以確保一致性


## Code Consistency Rules
  • Use async/await for all asynchronous operations
  • Import from @/utils for shared utilities
  • Follow barrel export pattern (index.ts)
  • Error handling: use AppError class with status codes
  • Date formatting: use dayjs, never native Date methods
  • API responses: use { data, error, meta } format
  • Check existing utilities before creating new ones

6.2.建築護欄

// eslint-plugin-boundaries — enforce architecture:
{
  "rules": {
    "boundaries/element-types": [2, {
      "default": "disallow",
      "rules": [
        // Controllers can import services, not other controllers
        { "from": "controllers", "allow": ["services", "types"] },
        // Services can import repositories, not controllers
        { "from": "services", "allow": ["repositories", "types"] },
      ]
    }]
  }
}

6.3.定期債務衝刺

// Dùng AI để plan refactoring sprint:
@workspace Analyze the codebase and identify:
1. Top 5 files with highest complexity
2. Most duplicated code patterns
3. Unused dependencies and dead exports
4. Files that violate our architecture boundaries
Prioritize by impact and create a refactoring plan.

7. 指標追蹤技術債務

公制 工具 目標
程式碼流失 GitClear,git日誌分析 2週內<5%
重複 jscpd、SonarQube < 總程式碼庫的 3%
死程式碼 克尼普、ts-修剪 0 未使用的出口
複雜性 ESLint 複雜性規則 每個功能最多 15 個
依賴新鮮度 npm 過時,更新 沒有專業落後
測試覆蓋率 笑話報道 整體>80%

八、總結

黃金法則:如果可以的話,Vibe Coding 是很好的選擇 閱讀理解與維護 產生的每一行人工智慧程式碼。如果你不理解人工智慧寫的程式碼,那就是技術債。

策略 工具
預防 自訂指令、架構規則
偵測 knip、jscpd、SonarQube、AI 評論
解析度 人工智能辅助重构、债务冲刺
監控 指标仪表板、CI/CD 门

最後發表: 团队和生产中的 Vibe 编码 — 企業採用、CI/CD、協作以及 Vibe Coding 的未來。