{"slug":"coding-standards","title":"coding-standards","summary":"Baseline cross-project coding conventions for naming, readability, immutability, and code-quality review. Use detailed frontend or backend skills for framework-specific patterns. Use when reviewing code quality or naming with no framework-specific skill that applies.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:10.354816Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: coding-standards\ndescription: Baseline cross-project coding conventions for naming, readability, immutability, and code-quality review. Use detailed frontend or backend skills for framework-specific patterns. Use when reviewing code quality or naming with no framework-specific skill that applies.\nmetadata:\norigin: ECC</h2>\n<h1>Coding Standards &amp; Best Practices</h1>\n<p>Baseline coding conventions applicable across projects.</p>\n<p>This skill is the shared floor, not the detailed framework playbook.</p>\n<ul>\n<li>Use <code>frontend-patterns</code> for React, state, forms, rendering, and UI architecture.</li>\n<li>Use <code>backend-patterns</code> or <code>api-design</code> for repository/service layers, endpoint design, validation, and server-specific concerns.</li>\n<li>Use <code>rules/common/coding-style.md</code> when you need the shortest reusable rule layer instead of a full skill walkthrough.</li>\n</ul>\n<h2>When to Activate</h2>\n<ul>\n<li>Starting a new project or module</li>\n<li>Reviewing code for quality and maintainability</li>\n<li>Refactoring existing code to follow conventions</li>\n<li>Enforcing naming, formatting, or structural consistency</li>\n<li>Setting up linting, formatting, or type-checking rules</li>\n<li>Onboarding new contributors to coding conventions</li>\n</ul>\n<h2>Scope Boundaries</h2>\n<p>Activate this skill for:</p>\n<ul>\n<li>descriptive naming</li>\n<li>immutability defaults</li>\n<li>readability, KISS, DRY, and YAGNI enforcement</li>\n<li>error-handling expectations and code-smell review</li>\n</ul>\n<p>Do not use this skill as the primary source for:</p>\n<ul>\n<li>React composition, hooks, or rendering patterns</li>\n<li>backend architecture, API design, or database layering</li>\n<li>domain-specific framework guidance when a narrower ECC skill already exists</li>\n</ul>\n<h2>Code Quality Principles</h2>\n<h3>1. Readability First</h3>\n<ul>\n<li>Code is read more than written</li>\n<li>Clear variable and function names</li>\n<li>Self-documenting code preferred over comments</li>\n<li>Consistent formatting</li>\n</ul>\n<h3>2. KISS (Keep It Simple, Stupid)</h3>\n<ul>\n<li>Simplest solution that works</li>\n<li>Avoid over-engineering</li>\n<li>No premature optimization</li>\n<li>Easy to understand &gt; clever code</li>\n</ul>\n<h3>3. DRY (Don't Repeat Yourself)</h3>\n<ul>\n<li>Extract common logic into functions</li>\n<li>Create reusable components</li>\n<li>Share utilities across modules</li>\n<li>Avoid copy-paste programming</li>\n</ul>\n<h3>4. YAGNI (You Aren't Gonna Need It)</h3>\n<ul>\n<li>Don't build features before they're needed</li>\n<li>Avoid speculative generality</li>\n<li>Add complexity only when required</li>\n<li>Start simple, refactor when needed</li>\n</ul>\n<h2>TypeScript/JavaScript Standards</h2>\n<h3>Variable Naming</h3>\n<pre><code>// PASS: GOOD: Descriptive names\nconst marketSearchQuery = 'election'\nconst isUserAuthenticated = true\nconst totalRevenue = 1000\n\n// FAIL: BAD: Unclear names\nconst q = 'election'\nconst flag = true\nconst x = 1000\n</code></pre>\n<h3>Function Naming</h3>\n<pre><code>// PASS: GOOD: Verb-noun pattern\nasync function fetchMarketData(marketId: string) { }\nfunction calculateSimilarity(a: number[], b: number[]) { }\nfunction isValidEmail(email: string): boolean { }\n\n// FAIL: BAD: Unclear or noun-only\nasync function market(id: string) { }\nfunction similarity(a, b) { }\nfunction email(e) { }\n</code></pre>\n<h3>Immutability Pattern (CRITICAL)</h3>\n<pre><code>// PASS: ALWAYS use spread operator\nconst updatedUser = {\n  ...user,\n  name: 'New Name'\n}\n\nconst updatedArray = [...items, newItem]\n\n// FAIL: NEVER mutate directly\nuser.name = 'New Name'  // BAD\nitems.push(newItem)     // BAD\n</code></pre>\n<h3>Error Handling</h3>\n<pre><code>// PASS: GOOD: Comprehensive error handling\nasync function fetchData(url: string) {\n  try {\n    const response = await fetch(url)\n\n    if (!response.ok) {\n      throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n    }\n\n    return await response.json()\n  } catch (error) {\n    console.error('Fetch failed:', error)\n    throw new Error('Failed to fetch data')\n  }\n}\n\n// FAIL: BAD: No error handling\nasync function fetchData(url) {\n  const response = await fetch(url)\n  return response.json()\n}\n</code></pre>\n<h3>Async/Await Best Practices</h3>\n<pre><code>// PASS: GOOD: Parallel execution when possible\nconst [users, markets, stats] = await Promise.all([\n  fetchUsers(),\n  fetchMarkets(),\n  fetchStats()\n])\n\n// FAIL: BAD: Sequential when unnecessary\nconst users = await fetchUsers()\nconst markets = await fetchMarkets()\nconst stats = await fetchStats()\n</code></pre>\n<h3>Type Safety</h3>\n<pre><code>// PASS: GOOD: Proper types\ninterface Market {\n  id: string\n  name: string\n  status: 'active' | 'resolved' | 'closed'\n  created_at: Date\n}\n\nfunction getMarket(id: string): Promise&lt;Market&gt; {\n  // Implementation\n}\n\n// FAIL: BAD: Using 'any'\nfunction getMarket(id: any): Promise&lt;any&gt; {\n  // Implementation\n}\n</code></pre>\n<h2>React Best Practices</h2>\n<h3>Component Structure</h3>\n<pre><code>// PASS: GOOD: Functional component with types\ninterface ButtonProps {\n  children: React.ReactNode\n  onClick: () =&gt; void\n  disabled?: boolean\n  variant?: 'primary' | 'secondary'\n}\n\nexport function Button({\n  children,\n  onClick,\n  disabled = false,\n  variant = 'primary'\n}: ButtonProps) {\n  return (\n    &lt;button\n      onClick={onClick}\n      disabled={disabled}\n      className={`btn btn-${variant}`}\n    &gt;\n      {children}\n    &lt;/button&gt;\n  )\n}\n\n// FAIL: BAD: No types, unclear structure\nexport function Button(props) {\n  return &lt;button onClick={props.onClick}&gt;{props.children}&lt;/button&gt;\n}\n</code></pre>\n<h3>Custom Hooks</h3>\n<pre><code>// PASS: GOOD: Reusable custom hook\nexport function useDebounce&lt;T&gt;(value: T, delay: number): T {\n  const [debouncedValue, setDebouncedValue] = useState&lt;T&gt;(value)\n\n  useEffect(() =&gt; {\n    const handler = setTimeout(() =&gt; {\n      setDebouncedValue(value)\n    }, delay)\n\n    return () =&gt; clearTimeout(handler)\n  }, [value, delay])\n\n  return debouncedValue\n}\n\n// Usage\nconst debouncedQuery = useDebounce(searchQuery, 500)\n</code></pre>\n<h3>State Management</h3>\n<pre><code>// PASS: GOOD: Proper state updates\nconst [count, setCount] = useState(0)\n\n// Functional update for state based on previous state\nsetCount(prev =&gt; prev + 1)\n\n// FAIL: BAD: Direct state reference\nsetCount(count + 1)  // Can be stale in async scenarios\n</code></pre>\n<h3>Conditional Rendering</h3>\n<pre><code>// PASS: GOOD: Clear conditional rendering\n{isLoading &amp;&amp; &lt;Spinner /&gt;}\n{error &amp;&amp; &lt;ErrorMessage error={error} /&gt;}\n{data &amp;&amp; &lt;DataDisplay data={data} /&gt;}\n\n// FAIL: BAD: Ternary hell\n{isLoading ? &lt;Spinner /&gt; : error ? &lt;ErrorMessage error={error} /&gt; : data ? &lt;DataDisplay data={data} /&gt; : null}\n</code></pre>\n<h2>API Design Standards</h2>\n<h3>REST API Conventions</h3>\n<pre><code>GET    /api/markets              # List all markets\nGET    /api/markets/:id          # Get specific market\nPOST   /api/markets              # Create new market\nPUT    /api/markets/:id          # Update market (full)\nPATCH  /api/markets/:id          # Update market (partial)\nDELETE /api/markets/:id          # Delete market\n\n# Query parameters for filtering\nGET /api/markets?status=active&amp;limit=10&amp;offset=0\n</code></pre>\n<h3>Response Format</h3>\n<pre><code>// PASS: GOOD: Consistent response structure\ninterface ApiResponse&lt;T&gt; {\n  success: boolean\n  data?: T\n  error?: string\n  meta?: {\n    total: number\n    page: number\n    limit: number\n  }\n}\n\n// Success response\nreturn NextResponse.json({\n  success: true,\n  data: markets,\n  meta: { total: 100, page: 1, limit: 10 }\n})\n\n// Error response\nreturn NextResponse.json({\n  success: false,\n  error: 'Invalid request'\n}, { status: 400 })\n</code></pre>\n<h3>Input Validation</h3>\n<pre><code>import { z } from 'zod'\n\n// PASS: GOOD: Schema validation\nconst CreateMarketSchema = z.object({\n  name: z.string().min(1).max(200),\n  description: z.string().min(1).max(2000),\n  endDate: z.string().datetime(),\n  categories: z.array(z.string()).min(1)\n})\n\nexport async function POST(request: Request) {\n  const body = await request.json()\n\n  try {\n    const validated = CreateMarketSchema.parse(body)\n    // Proceed with validated data\n  } catch (error) {\n    if (error instanceof z.ZodError) {\n      return NextResponse.json({\n        success: false,\n        error: 'Validation failed',\n        details: error.issues\n      }, { status: 400 })\n    }\n  }\n}\n</code></pre>\n<h2>File Organization</h2>\n<h3>Project Structure</h3>\n<pre><code>src/\n├── app/                    # Next.js App Router\n│   ├── api/               # API routes\n│   ├── markets/           # Market pages\n│   └── (auth)/           # Auth pages (route groups)\n├── components/            # React components\n│   ├── ui/               # Generic UI components\n│   ├── forms/            # Form components\n│   └── layouts/          # Layout components\n├── hooks/                # Custom React hooks\n├── lib/                  # Utilities and configs\n│   ├── api/             # API clients\n│   ├── utils/           # Helper functions\n│   └── constants/       # Constants\n├── types/                # TypeScript types\n└── styles/              # Global styles\n</code></pre>\n<h3>File Naming</h3>\n<pre><code>components/Button.tsx          # PascalCase for components\nhooks/useAuth.ts              # camelCase with 'use' prefix\nlib/formatDate.ts             # camelCase for utilities\ntypes/market.types.ts         # camelCase with .types suffix\n</code></pre>\n<h2>Comments &amp; Documentation</h2>\n<h3>When to Comment</h3>\n<pre><code>// PASS: GOOD: Explain WHY, not WHAT\n// Use exponential backoff to avoid overwhelming the API during outages\nconst delay = Math.min(1000 * Math.pow(2, retryCount), 30000)\n\n// Deliberately using mutation here for performance with large arrays\nitems.push(newItem)\n\n// FAIL: BAD: Stating the obvious\n// Increment counter by 1\ncount++\n\n// Set name to user's name\nname = user.name\n</code></pre>\n<h3>JSDoc for Public APIs</h3>\n<pre><code>/**\n * Searches markets using semantic similarity.\n *\n * @param query - Natural language search query\n * @param limit - Maximum number of results (default: 10)\n * @returns Array of markets sorted by similarity score\n * @throws {Error} If OpenAI API fails or Redis unavailable\n *\n * @example\n * ```typescript\n * const results = await searchMarkets('election', 5)\n * console.log(results[0].name) // \"Trump vs Biden\"\n * ```\n */\nexport async function searchMarkets(\n  query: string,\n  limit: number = 10\n): Promise&lt;Market[]&gt; {\n  // Implementation\n}\n</code></pre>\n<h2>Performance Best Practices</h2>\n<h3>Memoization</h3>\n<pre><code>import { useMemo, useCallback } from 'react'\n\n// PASS: GOOD: Memoize expensive computations\n// Copy before sorting - Array.prototype.sort mutates in place\nconst sortedMarkets = useMemo(() =&gt; {\n  return [...markets].sort((a, b) =&gt; b.volume - a.volume)\n}, [markets])\n\n// PASS: GOOD: Memoize callbacks\nconst handleSearch = useCallback((query: string) =&gt; {\n  setSearchQuery(query)\n}, [])\n</code></pre>\n<h3>Lazy Loading</h3>\n<pre><code>import { lazy, Suspense } from 'react'\n\n// PASS: GOOD: Lazy load heavy components\nconst HeavyChart = lazy(() =&gt; import('./HeavyChart'))\n\nexport function Dashboard() {\n  return (\n    &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;\n      &lt;HeavyChart /&gt;\n    &lt;/Suspense&gt;\n  )\n}\n</code></pre>\n<h3>Database Queries</h3>\n<pre><code>// PASS: GOOD: Select only needed columns\nconst { data } = await supabase\n  .from('markets')\n  .select('id, name, status')\n  .limit(10)\n\n// FAIL: BAD: Select everything\nconst { data } = await supabase\n  .from('markets')\n  .select('*')\n</code></pre>\n<h2>Testing Standards</h2>\n<h3>Test Structure (AAA Pattern)</h3>\n<pre><code>test('calculates similarity correctly', () =&gt; {\n  // Arrange\n  const vector1 = [1, 0, 0]\n  const vector2 = [0, 1, 0]\n\n  // Act\n  const similarity = calculateCosineSimilarity(vector1, vector2)\n\n  // Assert\n  expect(similarity).toBe(0)\n})\n</code></pre>\n<h3>Test Naming</h3>\n<pre><code>// PASS: GOOD: Descriptive test names\ntest('returns empty array when no markets match query', () =&gt; { })\ntest('throws error when OpenAI API key is missing', () =&gt; { })\ntest('falls back to substring search when Redis unavailable', () =&gt; { })\n\n// FAIL: BAD: Vague test names\ntest('works', () =&gt; { })\ntest('test search', () =&gt; { })\n</code></pre>\n<h2>Code Smell Detection</h2>\n<p>Watch for these anti-patterns:</p>\n<h3>1. Long Functions</h3>\n<pre><code>// FAIL: BAD: Function &gt; 50 lines\nfunction processMarketData() {\n  // 100 lines of code\n}\n\n// PASS: GOOD: Split into smaller functions\nfunction processMarketData() {\n  const validated = validateData()\n  const transformed = transformData(validated)\n  return saveData(transformed)\n}\n</code></pre>\n<h3>2. Deep Nesting</h3>\n<pre><code>// FAIL: BAD: 5+ levels of nesting\nif (user) {\n  if (user.isAdmin) {\n    if (market) {\n      if (market.isActive) {\n        if (hasPermission) {\n          // Do something\n        }\n      }\n    }\n  }\n}\n\n// PASS: GOOD: Early returns\nif (!user) return\nif (!user.isAdmin) return\nif (!market) return\nif (!market.isActive) return\nif (!hasPermission) return\n\n// Do something\n</code></pre>\n<h3>3. Magic Numbers</h3>\n<pre><code>// FAIL: BAD: Unexplained numbers\nif (retryCount &gt; 3) { }\nsetTimeout(callback, 500)\n\n// PASS: GOOD: Named constants\nconst MAX_RETRIES = 3\nconst DEBOUNCE_DELAY_MS = 500\n\nif (retryCount &gt; MAX_RETRIES) { }\nsetTimeout(callback, DEBOUNCE_DELAY_MS)\n</code></pre>\n<p><strong>Remember</strong>: Code quality is not negotiable. Clear, maintainable code enables rapid development and confident refactoring.</p>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":12866,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:54:10.553288Z","sha256":"F8282172467606B4CF3BF3B16EB36173BA6E2DA067C5FDBA618DC7CD1C5B4298","sizeBytes":5769},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/coding-standards","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"E071BC69178EBBD89963B6CA0AC24F88E7C2D5EE0B19E8D7234CB24275C14E4D","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T16:55:55.047003Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/coding-standards"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}