coding-standards

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Coding Standards & Best Practices

编码标准与最佳实践

Universal coding standards applicable across all projects.
适用于所有项目的通用编码标准。

Code Quality Principles

代码质量原则

1. Readability First

1. 可读性优先

  • Code is read more than written
  • Clear variable and function names
  • Self-documenting code preferred over comments
  • Consistent formatting
  • 代码的阅读次数远多于编写次数
  • 清晰的变量与函数命名
  • 优先使用自文档化代码而非注释
  • 一致的格式规范

2. KISS (Keep It Simple, Stupid)

2. KISS(保持简单)

  • Simplest solution that works
  • Avoid over-engineering
  • No premature optimization
  • Easy to understand > clever code
  • 采用最简单的可行解决方案
  • 避免过度设计
  • 不要过早优化
  • 易于理解 > 炫技代码

3. DRY (Don't Repeat Yourself)

3. DRY(不要重复自己)

  • Extract common logic into functions
  • Create reusable components
  • Share utilities across modules
  • Avoid copy-paste programming
  • 将通用逻辑提取为函数
  • 创建可复用组件
  • 在模块间共享工具函数
  • 避免复制粘贴式编程

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

4. YAGNI(你不会需要它)

  • Don't build features before they're needed
  • Avoid speculative generality
  • Add complexity only when required
  • Start simple, refactor when needed
  • 不要在需要之前构建功能
  • 避免不必要的通用性设计
  • 仅在必要时增加复杂度
  • 从简单开始,需要时再重构

TypeScript/JavaScript Standards

TypeScript/JavaScript 编码标准

Variable Naming

变量命名

typescript
// ✅ GOOD: Descriptive names
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// ❌ BAD: Unclear names
const q = 'election'
const flag = true
const x = 1000
typescript
// ✅ 良好:具有描述性的命名
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

// ❌ 糟糕:命名不清晰
const q = 'election'
const flag = true
const x = 1000

Function Naming

函数命名

typescript
// ✅ 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) { }
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) { }

Immutability Pattern (CRITICAL)

不可变模式(至关重要)

typescript
// ✅ 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
typescript
// ✅ 始终使用扩展运算符
const updatedUser = {
  ...user,
  name: 'New Name'
}

const updatedArray = [...items, newItem]

// ❌ 绝不要直接修改原数据
user.name = 'New Name'  // 糟糕
items.push(newItem)     // 糟糕

Error Handling

错误处理

typescript
// ✅ 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()
}
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 Best Practices

Async/Await 最佳实践

typescript
// ✅ 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()
typescript
// ✅ 良好:尽可能并行执行
const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

// ❌ 糟糕:不必要的顺序执行
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()

Type Safety

类型安全

typescript
// ✅ 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
}
typescript
// ✅ 良好:使用正确的类型定义
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 Best Practices

React 最佳实践

Component Structure

组件结构

typescript
// ✅ GOOD: Functional component with types
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>
  )
}

// ❌ BAD: No types, unclear structure
export function Button(props) {
  return <button onClick={props.onClick}>{props.children}</button>
}
typescript
// ✅ 良好:带类型定义的函数式组件
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>
}

Custom Hooks

自定义 Hooks

typescript
// ✅ GOOD: Reusable custom 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
}

// Usage
const debouncedQuery = useDebounce(searchQuery, 500)
typescript
// ✅ 良好:可复用的自定义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)

State Management

状态管理

typescript
// ✅ GOOD: Proper state updates
const [count, setCount] = useState(0)

// Functional update for state based on previous state
setCount(prev => prev + 1)

// ❌ BAD: Direct state reference
setCount(count + 1)  // Can be stale in async scenarios
typescript
// ✅ 良好:正确的状态更新方式
const [count, setCount] = useState(0)

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

// ❌ 糟糕:直接引用状态值
setCount(count + 1)  // 在异步场景中可能出现状态过期问题

Conditional Rendering

条件渲染

typescript
// ✅ GOOD: Clear conditional rendering
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// ❌ BAD: Ternary hell
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
typescript
// ✅ 良好:清晰的条件渲染
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}

// ❌ 糟糕:嵌套过深的三元表达式
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}

API Design Standards

API 设计标准

REST API Conventions

REST API 约定

GET    /api/markets              # List all markets
GET    /api/markets/:id          # Get specific market
POST   /api/markets              # Create new market
PUT    /api/markets/:id          # Update market (full)
PATCH  /api/markets/:id          # Update market (partial)
DELETE /api/markets/:id          # Delete market
GET    /api/markets              # 获取所有市场列表
GET    /api/markets/:id          # 获取指定市场详情
POST   /api/markets              # 创建新市场
PUT    /api/markets/:id          # 完整更新市场信息
PATCH  /api/markets/:id          # 部分更新市场信息
DELETE /api/markets/:id          # 删除市场

Query parameters for filtering

用于过滤的查询参数

GET /api/markets?status=active&limit=10&offset=0
undefined
GET /api/markets?status=active&limit=10&offset=0
undefined

Response Format

响应格式

typescript
// ✅ GOOD: Consistent response structure
interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

// Success response
return NextResponse.json({
  success: true,
  data: markets,
  meta: { total: 100, page: 1, limit: 10 }
})

// Error response
return NextResponse.json({
  success: false,
  error: 'Invalid request'
}, { status: 400 })
typescript
// ✅ 良好:一致的响应结构
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 })

Input Validation

输入验证

typescript
import { z } from 'zod'

// ✅ GOOD: Schema validation
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)
    // Proceed with validated data
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({
        success: false,
        error: 'Validation failed',
        details: error.errors
      }, { status: 400 })
    }
  }
}
typescript
import { z } from 'zod'

// ✅ 良好:使用Schema验证
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.errors
      }, { status: 400 })
    }
  }
}

File Organization

文件组织规范

Project Structure

项目结构

src/
├── app/                    # Next.js App Router
│   ├── api/               # API routes
│   ├── markets/           # Market pages
│   └── (auth)/           # Auth pages (route groups)
├── components/            # React components
│   ├── ui/               # Generic UI components
│   ├── forms/            # Form components
│   └── layouts/          # Layout components
├── hooks/                # Custom React hooks
├── lib/                  # Utilities and configs
│   ├── api/             # API clients
│   ├── utils/           # Helper functions
│   └── constants/       # Constants
├── types/                # TypeScript types
└── styles/              # Global styles
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/              # 全局样式

File Naming

文件命名

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
components/Button.tsx          # 组件使用大驼峰命名
hooks/useAuth.ts              # Hook使用小驼峰并以'use'为前缀
lib/formatDate.ts             # 工具函数使用小驼峰命名
types/market.types.ts         # 类型文件使用小驼峰并以.types为后缀

Comments & Documentation

注释与文档规范

When to Comment

何时添加注释

typescript
// ✅ 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
typescript
// ✅ 良好:解释原因,而非描述行为
// 在服务中断时使用指数退避策略,避免压垮API
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)

// 为了处理大型数组的性能,此处刻意使用修改原数据的方式
items.push(newItem)

// ❌ 糟糕:陈述显而易见的内容
// 将计数器加1
count++

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

JSDoc for Public APIs

公共API的JSDoc注释

typescript
/**
 * 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
}
typescript
/**
 * 使用语义相似度搜索市场。
 *
 * @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[]> {
  // 实现逻辑
}

Performance Best Practices

性能最佳实践

Memoization

记忆化处理

typescript
import { useMemo, useCallback } from 'react'

// ✅ GOOD: Memoize expensive computations
const sortedMarkets = useMemo(() => {
  return markets.sort((a, b) => b.volume - a.volume)
}, [markets])

// ✅ GOOD: Memoize callbacks
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])
typescript
import { useMemo, useCallback } from 'react'

// ✅ 良好:对昂贵的计算进行记忆化
const sortedMarkets = useMemo(() => {
  return markets.sort((a, b) => b.volume - a.volume)
}, [markets])

// ✅ 良好:对回调函数进行记忆化
const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])

Lazy Loading

懒加载

typescript
import { lazy, Suspense } from 'react'

// ✅ GOOD: Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'))

export function Dashboard() {
  return (
    <Suspense fallback={<Spinner />}>
      <HeavyChart />
    </Suspense>
  )
}
typescript
import { lazy, Suspense } from 'react'

// ✅ 良好:懒加载大型组件
const HeavyChart = lazy(() => import('./HeavyChart'))

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

Database Queries

数据库查询

typescript
// ✅ GOOD: Select only needed columns
const { data } = await supabase
  .from('markets')
  .select('id, name, status')
  .limit(10)

// ❌ BAD: Select everything
const { data } = await supabase
  .from('markets')
  .select('*')
typescript
// ✅ 良好:仅选择需要的列
const { data } = await supabase
  .from('markets')
  .select('id, name, status')
  .limit(10)

// ❌ 糟糕:选择所有列
const { data } = await supabase
  .from('markets')
  .select('*')

Testing Standards

测试标准

Test Structure (AAA Pattern)

测试结构(AAA模式)

typescript
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)
})
typescript
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 Naming

测试命名

typescript
// ✅ 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', () => { })
typescript
// ✅ 良好:具有描述性的测试名称
test('当没有市场匹配关键词时返回空数组', () => { })
test('当OpenAI API密钥缺失时抛出错误', () => { })
test('当Redis不可用时回退到子串搜索', () => { })

// ❌ 糟糕:模糊的测试名称
test('works', () => { })
test('test search', () => { })

Code Smell Detection

代码异味检测

Watch for these anti-patterns:
注意以下反模式:

1. Long Functions

1. 过长函数

typescript
// ❌ 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)
}
typescript
// ❌ 糟糕:函数超过50行
function processMarketData() {
  // 100行代码
}

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

2. Deep Nesting

2. 深层嵌套

typescript
// ❌ 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
typescript
// ❌ 糟糕:嵌套层级超过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. Magic Numbers

3. 魔法数字

typescript
// ❌ 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)
Remember: Code quality is not negotiable. Clear, maintainable code enables rapid development and confident refactoring.
typescript
// ❌ 糟糕:未解释的数字
if (retryCount > 3) { }
setTimeout(callback, 500)

// ✅ 良好:使用命名常量
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500

if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)
谨记:代码质量不容妥协。清晰、可维护的代码能够支撑快速开发与自信重构。