Communitygithub.com

코딩 표준

프로젝트 전반에 적용되는 기본 코딩 규칙으로, 이름 짓기, 가독성, 불변성 및 코드 품질 검토에 관한 기준을 제공합니다. 프레임워크별 패턴은 상세한 프론트엔드 또는 백엔드 스킬을 사용하세요.

코딩 표준란 무엇인가요?

이 '코딩 표준' 스킬은 프레임워크에 구애받지 않는 기본 코딩 규칙에 대한 참조 기준을 제공합니다. 프로젝트 전반에 걸쳐 일관된 이름 지정, 가독성, KISS, DRY, YAGNI 원칙을 강제하고, 불변성 패턴과 기본적인 오류 처리 모범 사례를 제시합니다. TypeScript/JavaScript, React, REST API 설계에 대한 구체적인 코드 예제를 포함하며, 파일 구조화, 성능 최적화, 테스트 작성 및 코드 냄새 탐지 방법도 다룹니다. 이 스킬은 프레임워크별 패턴을 다루는 `frontend-patterns` 또는 `backend-patterns` 같은 상세 스킬과 함께 사용되어야 합니다.

지원 대상~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/coding-standards

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

코딩 표준 및 모범 사례

프로젝트 전반에 적용되는 기본 코딩 규칙입니다.

이 스킬은 공유 기반 레이어이며, 상세한 프레임워크 설명서가 아닙니다.

  • React, 상태, 폼, 렌더링 및 UI 아키텍처에는 frontend-patterns를 사용하세요.
  • 저장소/서비스 레이어, 엔드포인트 설계, 유효성 검사 및 서버 관련 사항에는 backend-patterns 또는 api-design을 사용하세요.
  • 전체 스킬 설명서 대신 가장 짧은 재사용 가능한 규칙 레이어가 필요하면 rules/common/coding-style.md를 사용하세요.

활성화 시점

  • 새 프로젝트나 모듈을 시작할 때
  • 코드 품질과 유지보수성을 검토할 때
  • 기존 코드를 규칙에 맞게 리팩터링할 때
  • 이름 지정, 포맷팅 또는 구조적 일관성을 강제할 때
  • 린터, 포맷터 또는 타입 검사 규칙을 설정할 때
  • 새 기여자에게 코딩 규칙을 교육할 때

범위 경계

다음 상황에서 이 스킬을 활성화하세요:

  • 설명적인 이름 짓기
  • 기본 불변성
  • 가독성, KISS, DRY, YAGNI 준수
  • 오류 처리 기대치 및 코드 냄새 검토

다음 경우에는 이 스킬을 기본 출처로 사용하지 마세요:

  • React 구성, 훅, 렌더링 패턴
  • 백엔드 아키텍처, 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>
}

커스텀 훅

// 통과: 좋음: 재사용 가능한 커스텀 훅
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 훅
├── 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

주석 및 문서화

주석을 달아야 할 때

// 통과: 좋음: 무엇보다 왜(WHY)를 설명
// 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.

관련 스킬