关于 coding-standards
coding-standards 是适用于各类项目的编码规范技能,供开发者在编写、评审和重构代码时参考。内容涵盖可读性、简洁性、类型安全、测试与文件组织等实践。
主要功能
- 01强调清晰命名与一致格式
- 02倡导简单实现并避免重复
- 03提供 TypeScript/JavaScript 规范
- 04涵盖错误处理与异步实践
- 05指导测试、文档和文件组织
适用场景
- 01为新项目或模块制定规范
- 02评审代码的质量与可维护性
- 03重构代码以遵循约定
- 04为贡献者说明团队编码惯例
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ helloggx/ skill --skill coding-standards安装后在 Claude Code 中输入/coding-standards确认已加载。
详细介绍
编码标准与最佳实践
适用于所有项目的通用编码标准。
何时启用
- 开始新项目或模块时
- 审查代码的质量和可维护性时
- 重构现有代码以遵循约定时
- 强制统一命名、格式或结构时
- 设置 lint、格式化或类型检查规则时
- 帮助新贡献者熟悉编码约定时
代码质量原则
1. 可读性优先
- 代码的阅读次数多于编写次数
- 使用清晰的变量名和函数名
- 优先编写自解释代码,而非添加注释
- 保持格式一致
2. KISS(保持简单,笨蛋)
- 选择能解决问题的最简单方案
- 避免过度设计
- 不要过早优化
- 易于理解 > 代码炫技
3. DRY(不要重复自己)
- 将通用逻辑提取到函数中
- 创建可复用组件
- 在各模块间共享工具函数
- 避免复制粘贴式编程
4. YAGNI(你不会需要它)
- 不要在功能尚未需要时就构建它
- 避免推测性通用化
- 仅在必要时增加复杂度
- 从简单方案开始,在需要时再重构
TypeScript/JavaScript 标准
变量命名
// ✅ GOOD: Descriptive names
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
// ❌ BAD: Unclear names
const q = 'election'
const flag = true
const x = 1000
函数命名
// ✅ GOOD: Verb-noun pattern
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }
// ❌ BAD: Unclear or noun-only
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
不可变性模式(重要)
// ✅ ALWAYS use spread operator
const updatedUser = {
...user,
name: 'New Name'
}
const updatedArray = [...items, newItem]
// ❌ NEVER mutate directly
user.name = 'New Name' // BAD
items.push(newItem) // BAD
错误处理
// ✅ GOOD: Comprehensive error handling
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')
}
}
// ❌ BAD: No error handling
async function fetchData(url) {
const response = await fetch(url)
return response.json()
}
Async/Await 最佳实践
// ✅ GOOD: Parallel execution when possible
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
// ❌ BAD: Sequential when unnecessary
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
类型安全
// ✅ GOOD: Proper types
interface Market {
id: string
name: string
status: 'active' | 'resolved' | 'closed'
created_at: Date
}
function getMarket(id: string): Promise<Market> {
// Implementation
}
// ❌ BAD: Using 'any'
function getMarket(id: any): Promise<any> {
// Implementation
}
文件组织
文件命名
components/Button.tsx # PascalCase for components
hooks/useAuth.ts # camelCase with 'use' prefix
lib/formatDate.ts # camelCase for utilities
types/market.types.ts # camelCase with .types suffix
注释与文档
何时添加注释
// ✅ GOOD: Explain WHY, not WHAT
// Use exponential backoff to avoid overwhelming the API during outages
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)
// Deliberately using mutation here for performance with large arrays
items.push(newItem)
// ❌ BAD: Stating the obvious
// Increment counter by 1
count++
// Set name to user's name
name = user.name
公共 API 的 JSDoc
/**
* Searches markets using semantic similarity.
*
* @param query - Natural language search query
* @param limit - Maximum number of results (default: 10)
* @returns Array of markets sorted by similarity score
* @throws {Error} If OpenAI API fails or Redis unavailable
*
* @example
* ```typescript
* const results = await searchMarkets('election', 5)
* console.log(results[0].name) // "Trump vs Biden"
* ```
*/
export async function searchMarkets(
query: string,
limit: number = 10
): Promise<Market[]> {
// Implementation
}
测试标准
测试结构(AAA 模式)
test('calculates similarity correctly', () => {
// Arrange
const vector1 = [1, 0, 0]
const vector2 = [0, 1, 0]
// Act
const similarity = calculateCosineSimilarity(vector1, vector2)
// Assert
expect(similarity).toBe(0)
})
测试命名
// ✅ GOOD: Descriptive test names
test('returns empty array when no markets match query', () => { })
test('throws error when OpenAI API key is missing', () => { })
test('falls back to substring search when Redis unavailable', () => { })
// ❌ BAD: Vague test names
test('works', () => { })
test('test search', () => { })
代码异味检测
留意以下反模式:
1. 函数过长
// ❌ BAD: Function > 50 lines
function processMarketData() {
// 100 lines of code
}
// ✅ GOOD: Split into smaller functions
function processMarketData() {
const validated = validateData()
const transformed = transformData(validated)
return saveData(transformed)
}
2. 嵌套过深
// ❌ BAD: 5+ levels of nesting
if (user) {
if (user.isAdmin) {
if (market) {
if (market.isActive) {
if (hasPermission) {
// Do something
}
}
}
}
}
// ✅ GOOD: Early returns
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return
// Do something
3. 魔法数字
// ❌ BAD: Unexplained numbers
if (retryCount > 3) { }
setTimeout(callback, 500)
// ✅ GOOD: Named constants
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500
if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)
请记住:代码质量不容妥协。清晰、可维护的代码有助于快速开发,并让重构更有把握。
评论
支持 Markdown