Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development.
Coding Standards & Best Practices
Universal coding standards applicable across all projects.
Code Quality Principles
1. Readability First
- 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)
- Simplest solution that works
- Avoid over-engineering
- No premature optimization
- Easy to understand > clever code
3. DRY (Don't Repeat Yourself)
- Extract common logic into functions
- Create reusable components
- Share utilities across modules
- Avoid copy-paste programming
4. YAGNI (You Aren't Gonna Need It)
- Don't build features before they're needed
- Avoid speculative generality
- Add complexity only when required
- Start simple, refactor when needed
TypeScript/JavaScript Standards
Variable Naming
1// ✅ GOOD: Descriptive names
2const marketSearchQuery = 'election'
3const isUserAuthenticated = true
4const totalRevenue = 1000
5
6// ❌ BAD: Unclear names
7const q = 'election'
8const flag = true
9const x = 1000Function Naming
1// ✅ GOOD: Verb-noun pattern
2async function fetchMarketData(marketId: string) { }
3function calculateSimilarity(a: number[], b: number[]) { }
4function isValidEmail(email: string): boolean { }
5
6// ❌ BAD: Unclear or noun-only
7async function market(id: string) { }
8function similarity(a, b) { }
9function email(e) { }Immutability Pattern (CRITICAL)
1// ✅ ALWAYS use spread operator
2const updatedUser = {
3 ...user,
4 name: 'New Name'
5}
6
7const updatedArray = [...items, newItem]
8
9// ❌ NEVER mutate directly
10user.name = 'New Name' // BAD
11items.push(newItem) // BADError Handling
1// ✅ GOOD: Comprehensive error handling
2async function fetchData(url: string) {
3 try {
4 const response = await fetch(url)
5
6 if (!response.ok) {
7 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
8 }
9
10 return await response.json()
11 } catch (error) {
12 console.error('Fetch failed:', error)
13 throw new Error('Failed to fetch data')
14 }
15}
16
17// ❌ BAD: No error handling
18async function fetchData(url) {
19 const response = await fetch(url)
20 return response.json()
21}Async/Await Best Practices
1// ✅ GOOD: Parallel execution when possible
2const [users, markets, stats] = await Promise.all([
3 fetchUsers(),
4 fetchMarkets(),
5 fetchStats()
6])
7
8// ❌ BAD: Sequential when unnecessary
9const users = await fetchUsers()
10const markets = await fetchMarkets()
11const stats = await fetchStats()Type Safety
1// ✅ GOOD: Proper types
2interface Market {
3 id: string
4 name: string
5 status: 'active' | 'resolved' | 'closed'
6 created_at: Date
7}
8
9function getMarket(id: string): Promise<Market> {
10 // Implementation
11}
12
13// ❌ BAD: Using 'any'
14function getMarket(id: any): Promise<any> {
15 // Implementation
16}React Best Practices
Component Structure
1// ✅ GOOD: Functional component with types
2interface ButtonProps {
3 children: React.ReactNode
4 onClick: () => void
5 disabled?: boolean
6 variant?: 'primary' | 'secondary'
7}
8
9export function Button({
10 children,
11 onClick,
12 disabled = false,
13 variant = 'primary'
14}: ButtonProps) {
15 return (
16 <button
17 onClick={onClick}
18 disabled={disabled}
19 className={`btn btn-${variant}`}
20 >
21 {children}
22 </button>
23 )
24}
25
26// ❌ BAD: No types, unclear structure
27export function Button(props) {
28 return <button onClick={props.onClick}>{props.children}</button>
29}Custom Hooks
1// ✅ GOOD: Reusable custom hook
2export function useDebounce<T>(value: T, delay: number): T {
3 const [debouncedValue, setDebouncedValue] = useState<T>(value)
4
5 useEffect(() => {
6 const handler = setTimeout(() => {
7 setDebouncedValue(value)
8 }, delay)
9
10 return () => clearTimeout(handler)
11 }, [value, delay])
12
13 return debouncedValue
14}
15
16// Usage
17const debouncedQuery = useDebounce(searchQuery, 500)State Management
1// ✅ GOOD: Proper state updates
2const [count, setCount] = useState(0)
3
4// Functional update for state based on previous state
5setCount(prev => prev + 1)
6
7// ❌ BAD: Direct state reference
8setCount(count + 1) // Can be stale in async scenariosConditional Rendering
1// ✅ GOOD: Clear conditional rendering
2{isLoading && <Spinner />}
3{error && <ErrorMessage error={error} />}
4{data && <DataDisplay data={data} />}
5
6// ❌ BAD: Ternary hell
7{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}API Design Standards
REST API Conventions
1GET /api/markets # List all markets
2GET /api/markets/:id # Get specific market
3POST /api/markets # Create new market
4PUT /api/markets/:id # Update market (full)
5PATCH /api/markets/:id # Update market (partial)
6DELETE /api/markets/:id # Delete market
7
8# Query parameters for filtering
9GET /api/markets?status=active&limit=10&offset=0Response Format
1// ✅ GOOD: Consistent response structure
2interface ApiResponse<T> {
3 success: boolean
4 data?: T
5 error?: string
6 meta?: {
7 total: number
8 page: number
9 limit: number
10 }
11}
12
13// Success response
14return NextResponse.json({
15 success: true,
16 data: markets,
17 meta: { total: 100, page: 1, limit: 10 }
18})
19
20// Error response
21return NextResponse.json({
22 success: false,
23 error: 'Invalid request'
24}, { status: 400 })Input Validation
1import { z } from 'zod'
2
3// ✅ GOOD: Schema validation
4const CreateMarketSchema = z.object({
5 name: z.string().min(1).max(200),
6 description: z.string().min(1).max(2000),
7 endDate: z.string().datetime(),
8 categories: z.array(z.string()).min(1)
9})
10
11export async function POST(request: Request) {
12 const body = await request.json()
13
14 try {
15 const validated = CreateMarketSchema.parse(body)
16 // Proceed with validated data
17 } catch (error) {
18 if (error instanceof z.ZodError) {
19 return NextResponse.json({
20 success: false,
21 error: 'Validation failed',
22 details: error.errors
23 }, { status: 400 })
24 }
25 }
26}File Organization
Project Structure
1src/
2├── app/ # Next.js App Router
3│ ├── api/ # API routes
4│ ├── markets/ # Market pages
5│ └── (auth)/ # Auth pages (route groups)
6├── components/ # React components
7│ ├── ui/ # Generic UI components
8│ ├── forms/ # Form components
9│ └── layouts/ # Layout components
10├── hooks/ # Custom React hooks
11├── lib/ # Utilities and configs
12│ ├── api/ # API clients
13│ ├── utils/ # Helper functions
14│ └── constants/ # Constants
15├── types/ # TypeScript types
16└── styles/ # Global stylesFile Naming
1components/Button.tsx # PascalCase for components
2hooks/useAuth.ts # camelCase with 'use' prefix
3lib/formatDate.ts # camelCase for utilities
4types/market.types.ts # camelCase with .types suffixComments & Documentation
When to Comment
1// ✅ GOOD: Explain WHY, not WHAT
2// Use exponential backoff to avoid overwhelming the API during outages
3const delay = Math.min(1000 * Math.pow(2, retryCount), 30000)
4
5// Deliberately using mutation here for performance with large arrays
6items.push(newItem)
7
8// ❌ BAD: Stating the obvious
9// Increment counter by 1
10count++
11
12// Set name to user's name
13name = user.nameJSDoc for Public APIs
1/**
2 * Searches markets using semantic similarity.
3 *
4 * @param query - Natural language search query
5 * @param limit - Maximum number of results (default: 10)
6 * @returns Array of markets sorted by similarity score
7 * @throws {Error} If OpenAI API fails or Redis unavailable
8 *
9 * @example
10 * ```typescript
11 * const results = await searchMarkets('election', 5)
12 * console.log(results[0].name) // "Trump vs Biden"
13 * ```
14 */
15export async function searchMarkets(
16 query: string,
17 limit: number = 10
18): Promise<Market[]> {
19 // Implementation
20}Performance Best Practices
Memoization
1import { useMemo, useCallback } from 'react'
2
3// ✅ GOOD: Memoize expensive computations
4const sortedMarkets = useMemo(() => {
5 return markets.sort((a, b) => b.volume - a.volume)
6}, [markets])
7
8// ✅ GOOD: Memoize callbacks
9const handleSearch = useCallback((query: string) => {
10 setSearchQuery(query)
11}, [])Lazy Loading
1import { lazy, Suspense } from 'react'
2
3// ✅ GOOD: Lazy load heavy components
4const HeavyChart = lazy(() => import('./HeavyChart'))
5
6export function Dashboard() {
7 return (
8 <Suspense fallback={<Spinner />}>
9 <HeavyChart />
10 </Suspense>
11 )
12}Database Queries
1// ✅ GOOD: Select only needed columns
2const { data } = await supabase
3 .from('markets')
4 .select('id, name, status')
5 .limit(10)
6
7// ❌ BAD: Select everything
8const { data } = await supabase
9 .from('markets')
10 .select('*')Testing Standards
Test Structure (AAA Pattern)
1test('calculates similarity correctly', () => {
2 // Arrange
3 const vector1 = [1, 0, 0]
4 const vector2 = [0, 1, 0]
5
6 // Act
7 const similarity = calculateCosineSimilarity(vector1, vector2)
8
9 // Assert
10 expect(similarity).toBe(0)
11})Test Naming
1// ✅ GOOD: Descriptive test names
2test('returns empty array when no markets match query', () => { })
3test('throws error when OpenAI API key is missing', () => { })
4test('falls back to substring search when Redis unavailable', () => { })
5
6// ❌ BAD: Vague test names
7test('works', () => { })
8test('test search', () => { })Code Smell Detection
Watch for these anti-patterns:
1. Long Functions
1// ❌ BAD: Function > 50 lines
2function processMarketData() {
3 // 100 lines of code
4}
5
6// ✅ GOOD: Split into smaller functions
7function processMarketData() {
8 const validated = validateData()
9 const transformed = transformData(validated)
10 return saveData(transformed)
11}2. Deep Nesting
1// ❌ BAD: 5+ levels of nesting
2if (user) {
3 if (user.isAdmin) {
4 if (market) {
5 if (market.isActive) {
6 if (hasPermission) {
7 // Do something
8 }
9 }
10 }
11 }
12}
13
14// ✅ GOOD: Early returns
15if (!user) return
16if (!user.isAdmin) return
17if (!market) return
18if (!market.isActive) return
19if (!hasPermission) return
20
21// Do something3. Magic Numbers
1// ❌ BAD: Unexplained numbers
2if (retryCount > 3) { }
3setTimeout(callback, 500)
4
5// ✅ GOOD: Named constants
6const MAX_RETRIES = 3
7const DEBOUNCE_DELAY_MS = 500
8
9if (retryCount > MAX_RETRIES) { }
10setTimeout(callback, DEBOUNCE_DELAY_MS)Remember: Code quality is not negotiable. Clear, maintainable code enables rapid development and confident refactoring.