[ PROMPT_NODE_23794 ]
coding-standards
[ SKILL_DOCUMENTATION ]
# 编码标准与最佳实践
适用于所有项目的通用编码标准。
## 代码质量原则
### 1. 可读性优先
- 代码被阅读的次数远多于编写的次数
- 清晰的变量和函数命名
- 优先使用自解释代码而非注释
- 保持格式一致性
### 2. KISS 原则 (保持简单)
- 使用最简单有效的解决方案
- 避免过度工程
- 不要过早优化
- 易于理解 > 巧妙的代码
### 3. DRY 原则 (不要重复自己)
- 将通用逻辑提取为函数
- 创建可重用组件
- 在模块间共享工具函数
- 避免复制粘贴式编程
### 4. YAGNI 原则 (你不会需要它)
- 在真正需要之前不要构建功能
- 避免推测性的通用化
- 仅在必要时增加复杂性
- 从简单开始,按需重构
## TypeScript/JavaScript 标准
### 变量命名
typescript
// ✅ 推荐:描述性命名
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
// ❌ 不推荐:命名不清晰
const q = 'election'
const flag = true
const x = 1000
### 函数命名
typescript
// ✅ 推荐:动词-名词模式
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }
// ❌ 不推荐:不清晰或仅有名词
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
### 不可变性模式 (关键)
typescript
// ✅ 始终使用展开运算符
const updatedUser = {
...user,
name: 'New Name'
}
const updatedArray = [...items, newItem]
// ❌ 永远不要直接修改
user.name = 'New Name' // 错误
items.push(newItem) // 错误
### 错误处理
typescript
// ✅ 推荐:全面的错误处理
async function fetchData(url: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
return await response.json()
} catch (error) {
console.error('Fetch failed:', error)
throw new Error('Failed to fetch data')
}
}
// ❌ 不推荐:无错误处理
async function fetchData(url) {
const response = await fetch(url)
return response.json()
}
### Async/Await 最佳实践
typescript
// ✅ 推荐:尽可能并行执行
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
// ❌ 不推荐:不必要时串行执行
const users = a