Communitygithub.com

编码规范

跨项目的基线编码约定,涵盖命名、可读性、不可变性和代码质量审查。当没有特定框架的技能可使用时,用于审查代码质量或命名。

编码规范 是什么?

该技能为跨项目提供通用的编码规范,适用于代码审查、重构和引导新贡献者。它定义了核心的代码质量原则(可读性优先、KISS、DRY、YAGNI),并给出了TypeScript/JavaScript、React、API设计等领域的详细示例。该技能明确其适用范围:专注于命名、不可变性、代码异味检测和错误处理模式,不取代`frontend-patterns`或`backend-patterns`等更具体的框架技能。此外,它还涵盖了文件组织、注释习惯、性能优化(记忆化、懒加载)和测试标准(AAA模式)。

兼容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/coding-standards

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

编码规范与最佳实践

适用于各项目的基线编码约定。

此技能是共享的基础层,而非详细的框架操作手册。

  • 对于 React、状态、表单、渲染和 UI 架构,请使用 frontend-patterns。
  • 对于仓库/服务层、端点设计、验证和服务器特定问题,请使用 backend-patterns 或 api-design。
  • 当你需要最短的可复用规则层(而非完整技能指导)时,请使用 rules/common/coding-style.md。

何时激活

  • 启动新项目或新模块时
  • 审查代码质量和可维护性时
  • 重构现有代码以遵循规范时
  • 强制命名、格式化或结构一致性时
  • 设置 linting、格式化或类型检查规则时
  • 引导新贡献者熟悉编码规范时

范围边界

激活此技能以处理:

  • 描述性命名
  • 默认不可变性
  • 可读性、KISS、DRY 和 YAGNI 的强制执行
  • 错误处理预期和代码异味审查

以下情况请勿将此技能作为主要来源:

  • React 组合、hooks 或渲染模式
  • 后端架构、API 设计或数据库分层
  • 当已有更具体的 ECC 技能时,针对特定领域的框架指导

代码质量原则

1. 可读性优先

  • 代码被阅读的次数远多于编写的次数
  • 清晰的变量和函数名称
  • 倾向于自文档化代码,而非注释
  • 一致的格式

2. KISS (Keep It Simple, Stupid)

  • 选择能工作的最简单方案
  • 避免过度工程化
  • 不要过早优化
  • 易于理解 > 巧妙的代码

3. DRY (Don't Repeat Yourself)

  • 将公共逻辑提取到函数中
  • 创建可复用的组件
  • 在模块间共享工具函数
  • 避免复制粘贴编程

4. YAGNI (You Aren't Gonna Need It)

  • 不要在需要之前构建功能
  • 避免推测性的通用性
  • 只在需要时增加复杂性
  • 从简单开始,必要时重构

TypeScript/JavaScript 标准

变量命名

// 通过:良好:描述性名称
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// 失败:不良:不清晰的名称
const q = 'election'
const flag = true
const x = 1000

函数命名

// 通过:良好:动词-名词模式
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) { }

不可变性模式(关键)

// 通过:始终使用展开运算符
const updatedUser = {
  ...user,
  name: 'New Name'
}

const updatedArray = [...items, newItem]

// 失败:绝不直接变异
user.name = 'New Name'  // 不良
items.push(newItem)     // 不良

错误处理

// 通过:良好:全面的错误处理
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 最佳实践

// 通过:良好:尽可能并行执行
const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

// 失败:不良:不必要时顺序执行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()

类型安全

// 通过:良好:适当的类型
interface Market {
  id: string
  name: string
  status: 'active' | 'resolved' | 'closed'
  created_at: Date
}

function getMarket(id: string): Promise<Market> {
  // 实现
}

// 失败:不良:使用 'any'
function getMarket(id: any): Promise<any> {
  // 实现
}

React 最佳实践

组件结构

// 通过:良好:带类型的函数组件
interface ButtonProps {
  children: React.ReactNode
  onClick: () => void
  disabled?: boolean
  variant?: 'primary' | 'secondary'
}

export function Button({
  children,
  onClick,
  disabled = false,
  variant = 'primary'
}: ButtonProps) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`btn btn-${variant}`}
    >
      {children}
    </button>
  )
}

// 失败:不良:无类型,结构不清晰
export function Button(props) {
  return <button onClick={props.onClick}>{props.children}</button>
}

自定义 Hooks

// 通过:良好:可复用的自定义 hook
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

// 使用
const debouncedQuery = useDebounce(searchQuery, 500)

状态管理

// 通过:良好:正确的状态更新
const [count, setCount] = useState(0)

// 基于前一个状态进行函数式更新
setCount(prev => prev + 1)

// 失败:不良:直接引用状态
setCount(count + 1)  // 在异步场景下可能过期

条件渲染

// 通过:良好:清晰的条件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// 失败:不良:三元运算符地狱
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}

API 设计标准

REST API 约定

GET    /api/markets              # 列出所有市场
GET    /api/markets/:id          # 获取特定市场
POST   /api/markets              # 创建新市场
PUT    /api/markets/:id          # 更新市场(全量)
PATCH  /api/markets/:id          # 更新市场(部分)
DELETE /api/markets/:id          # 删除市场

# 用于过滤的查询参数
GET /api/markets?status=active&limit=10&offset=0

响应格式

// 通过:良好:一致的响应结构
interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

// 成功响应
return NextResponse.json({
  success: true,
  data: markets,
  meta: { total: 100, page: 1, limit: 10 }
})

// 错误响应
return NextResponse.json({
  success: false,
  error: 'Invalid request'
}, { status: 400 })

输入验证

import { z } from 'zod'

// 通过:良好:模式验证
const CreateMarketSchema = z.object({
  name: z.string().min(1).max(200),
  description: z.string().min(1).max(2000),
  endDate: z.string().datetime(),
  categories: z.array(z.string()).min(1)
})

export async function POST(request: Request) {
  const body = await request.json()

  try {
    const validated = CreateMarketSchema.parse(body)
    // 使用已验证的数据继续
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({
        success: false,
        error: 'Validation failed',
        details: error.issues
      }, { status: 400 })
    }
  }
}

文件组织

项目结构

src/
├── app/                    # Next.js App Router
│   ├── api/               # API 路由
│   ├── markets/           # 市场页面
│   └── (auth)/           # 认证页面(路由组)
├── components/            # React 组件
│   ├── ui/               # 通用 UI 组件
│   ├── forms/            # 表单组件
│   └── layouts/          # 布局组件
├── hooks/                # 自定义 React hooks
├── lib/                  # 工具和配置
│   ├── api/             # API 客户端
│   ├── utils/           # 辅助函数
│   └── constants/       # 常量
├── types/                # TypeScript 类型
└── styles/              # 全局样式

文件命名

components/Button.tsx          # 组件使用 PascalCase
hooks/useAuth.ts              # 以 'use' 前缀使用 camelCase
lib/formatDate.ts             # 工具函数使用 camelCase
types/market.types.ts         # 以 .types 后缀使用 camelCase

注释与文档

何时注释

// 通过:良好:解释为什么,而不是什么
// 使用指数退避,以避免在中断期间压垮 API
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)

// 出于性能考虑,故意对大型数组使用变异
items.push(newItem)

// 失败:不良:陈述显而易见的内容
// 计数器加 1
count++

// 将名称设置为用户名称
name = user.name

公共 API 的 JSDoc

/**
 * 使用语义相似性搜索市场。
 *
 * @param query - 自然语言搜索查询
 * @param limit - 最大结果数(默认:10)
 * @returns 按相似度分数排序的市场数组
 * @throws {Error} 如果 OpenAI API 失败或 Redis 不可用
 *
 * @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[]> {
  // 实现
}

性能最佳实践

记忆化

import { useMemo, useCallback } from 'react'

// 通过:良好:记忆化昂贵的计算
// 排序前复制 - Array.prototype.sort 会原地变异
const sortedMarkets = useMemo(() => {
  return [...markets].sort((a, b) => b.volume - a.volume)
}, [markets])

// 通过:良好:记忆化回调
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])

懒加载

import { lazy, Suspense } from 'react'

// 通过:良好:懒加载重量级组件
const HeavyChart = lazy(() => import('./HeavyChart'))

export function Dashboard() {
  return (
    <Suspense fallback={<Spinner />}>
      <HeavyChart />
    </Suspense>
  )
}

数据库查询

// 通过:良好:只选择需要的列
const { data } = await supabase
  .from('markets')
  .select('id, name, status')
  .limit(10)

// 失败:不良:选择所有内容
const { data } = await supabase
  .from('markets')
  .select('*')

测试标准

测试结构(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)
})

测试命名

// 通过:良好:描述性测试名称
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', () => { })

// 失败:不良:模糊的测试名称
test('works', () => { })
test('test search', () => { })

代码异味检测

注意以下反模式:

1. 长函数

// 失败:不良:函数超过 50 行
function processMarketData() {
  // 100 行代码
}

// 通过:良好:拆分成更小的函数
function processMarketData() {
  const validated = validateData()
  const transformed = transformData(validated)
  return saveData(transformed)
}

2. 深层嵌套

// 失败:不良:5 层或更多嵌套
if (user) {
  if (user.isAdmin) {
    if (market) {
      if (market.isActive) {
        if (hasPermission) {
          // 做某事
        }
      }
    }
  }
}

// 通过:良好:提前返回
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return

// 做某事

3. 魔法数字

// 失败:不良:未解释的数字
if (retryCount > 3) { }
setTimeout(callback, 500)

// 通过:良好:命名常量
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500

if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)

请记住:代码质量不容妥协。清晰、可维护的代码能够支持快速开发和自信的重构。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能