claude-code/claude-zh/rules/common/coding-style.md

49 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 程式碼風格 (Coding Style)
## 不可變性 (Immutability - 關鍵)
始終建立新物件,**絕對不要** 修改現有物件:
```
// 偽代碼範例
錯誤modify(original, field, value) → 直接在原處 (in-place) 修改原始物件
正確update(original, field, value) → 返回包含變更的新副本
```
原理:不可變數據可以防止隱藏的副作用,使偵錯更容易,並能實現安全的併發處理。
## 檔案組織
**多個小檔案 > 少數大檔案**
- 高內聚,低耦合。
- 典型行數為 200-400 行,上限 800 行。
- 從大型模組中擷取工具函式 (Utilities)。
- 按功能/領域 (Feature/Domain) 組織,而非按類型。
## 錯誤處理 (Error Handling)
始終進行全面的錯誤處理:
- 在每個層級明確處理錯誤。
- 在面向 UI 的程式碼中提供對使用者友好的錯誤訊息。
- 在伺服器端記錄詳細的錯誤上下文。
- 絕對不要靜默地吞掉 (Swallow) 錯誤。
## 輸入驗證 (Input Validation)
在系統邊界處始終進行驗證:
- 在處理前驗證所有使用者輸入。
- 使用基於 Schema 的驗證(若可用)。
- 使用清晰的錯誤訊息實施「快速失敗 (Fail fast)」。
- 絕對不要信任外部數據API 回應、使用者輸入、檔案內容)。
## 程式碼品質檢核清單
在標記工作完成之前:
- [ ] 程式碼具備可讀性且命名良好。
- [ ] 函式精簡 (<50 )。
- [ ] 檔案焦點明確 (<800 )。
- [ ] 無過深巢狀 (>4 層)。
- [ ] 具備正確的錯誤處理。
- [ ] 無硬編碼數值 (使用常數或配置)。
- [ ] 無物件修改 (使用不可變模式)。