Communitygithub.com

編碼標準

跨專案通用的基本編碼慣例,涵蓋命名、可讀性、不可變性與程式碼品質審查。當沒有特定框架技能可套用時,請於審查程式碼品質或命名時使用。

編碼標準 是什麼?

此技能定義了跨專案共享的基礎編碼標準與最佳實務,作為程式碼品質的最低門檻,而非特定框架的詳細指南。其核心原則包括可讀性優先(KISS)、避免重複(DRY)與不做過度設計(YAGNI),並涵蓋命名慣例、不可變性模式、錯誤處理、非同步/等待最佳實務、型別安全等主題。此技能適用於任何程式碼審查或重構場景,並明確指出應於何時轉而使用更專精的技能(如 frontend-patterns 或 backend-patterns)。支援平台包括所有使用 TypeScript/JavaScript 的專案,尤其適合 Next.js 與 React 應用,並提供具體的程式碼範例與反模式比較,協助開發者與 AI 代理快速執行一致的品質檢查。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

編碼標準與最佳實務

跨專案通用的基本編碼慣例。

此技能是共享的基礎規範,而非詳細的框架手冊。

  • 使用 frontend-patterns 處理 React、狀態、表單、渲染與 UI 架構。
  • 使用 backend-patterns 或 api-design 處理儲存庫/服務層、端點設計、驗證與伺服器特定議題。
  • 若只需要最簡潔的可重複使用規則層,而非完整的技能逐步解說,請使用 rules/common/coding-style.md。

啟用時機

  • 啟動新專案或模組時
  • 審查程式碼的品質與可維護性時
  • 重構現有程式碼以符合慣例時
  • 強制執行命名、格式化或結構一致性時
  • 設定 linting、格式化或型別檢查規則時
  • 引導新貢獻者了解編碼慣例時

範圍界限

啟用此技能以處理:

  • 描述性命名
  • 預設不可變性
  • 可讀性、KISS、DRY 與 YAGNI 的強制執行
  • 錯誤處理期望與程式碼異味審查

請勿將此技能當作下列領域的主要來源:

  • React 組合、hooks 或渲染模式
  • 後端架構、API 設計或資料庫分層
  • 領域特定的框架指引,當已有更精確的 ECC 技能存在時

程式碼品質原則

1. 可讀性優先

  • 程式碼被閱讀的次數遠多於撰寫的次數
  • 清晰易懂的變數與函式名稱
  • 偏好自我說明的程式碼,而非註解
  • 一致的格式化

2. KISS(保持簡單,笨蛋)

  • 使用最簡單且能正常運作的解決方案
  • 避免過度工程化
  • 不做過早最佳化
  • 易於理解勝過巧妙程式碼

3. DRY(避免重複)

  • 將共同邏輯抽取成函式
  • 建立可重複使用的元件
  • 跨模組共享工具程式
  • 避免複製貼上編寫方式

4. YAGNI(你不需要它)

  • 不要在需要之前就建構功能
  • 避免投機的通用設計
  • 僅在必要時增加複雜度
  • 從簡單開始,需要時重構

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()
}

非同步/等待最佳實務

// 通過:良好:盡可能並行執行
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'

// 通過:良好: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.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              # camelCase 並加上 'use' 前綴
lib/formatDate.ts             # camelCase 用於工具
 types/market.types.ts         # camelCase 並加上 .types 後綴

註解與文件

何時加入註解

// 通過:良好:解釋「為什麼」而非「做什麼」
// 使用指數退避以避免在服務中斷期間對 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.

相關技能