| name | coding-standards |
| description | Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development.
Use when writing any code to ensure consistent quality.
|
| allowed-tools | Read, Write, Edit, Grep, Glob |
Coding Standards & Best Practices
Code Quality Principles
1. Readability First
- Code is read more than written
- Clear variable and function names
- Self-documenting code preferred over comments
2. KISS (Keep It Simple, Stupid)
- Simplest solution that works
- Avoid over-engineering
- Easy to understand > clever code
3. DRY (Don't Repeat Yourself)
- Extract common logic into functions
- Create reusable components
4. YAGNI (You Aren't Gonna Need It)
- Don't build features before they're needed
- Start simple, refactor when needed
TypeScript/JavaScript Standards
Variable Naming
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
const q = 'election'
const flag = true
const x = 1000
Function Naming
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) { }
Immutability Pattern (CRITICAL)
const updatedUser = {
...user,
name: 'New Name'
}
const updatedArray = [...items, newItem]
user.name = 'New Name'
items.push(newItem)
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')
}
}
async function fetchData(url) {
const response = await fetch(url)
return response.json()
}
Async/Await Best Practices
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
Type Safety
interface Market {
id: string
name: string
status: 'active' | 'resolved' | 'closed'
}
function getMarket(id: string): Promise<Market> {
}
function getMarket(id: any): Promise<any> {
}
React Best Practices
Component Structure
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>
)
}
Custom Hooks
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
}
State Management
setCount(prev => prev + 1)
setCount(count + 1)
Conditional Rendering
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}
{isLoading ? <Spinner /> : error ? <ErrorMessage /> : data ? <DataDisplay /> : null}
API Design Standards
Response Format
interface ApiResponse<T> {
success: boolean
data?: T
error?: string
meta?: {
total: number
page: number
limit: number
}
}
return { success: true, data: markets, meta: { total: 100, page: 1, limit: 10 } }
return { success: false, error: 'Invalid request' }
Input Validation
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()
})
const validated = CreateMarketSchema.parse(body)
File Organization
Many Small Files > Few Large Files
- 200-400 lines typical
- 800 lines maximum
- High cohesion, low coupling
- Single responsibility per file
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
Code Smell Detection
Long Functions (>50 lines)
function processMarketData() {
}
function processMarketData() {
const validated = validateData()
const transformed = transformData(validated)
return saveData(transformed)
}
Deep Nesting (>4 levels)
if (user) {
if (user.isAdmin) {
if (market) {
}
}
}
if (!user) return
if (!user.isAdmin) return
if (!market) return
Magic Numbers
if (retryCount > 3) { }
const MAX_RETRIES = 3
if (retryCount > MAX_RETRIES) { }
Checklist