Writing

Writing Effective Code Examples

Create code examples that users can trust, understand, and successfully implement in their projects.

Code examples are often the first thing developers look for in documentation. Make them count by ensuring they're accurate, complete, and genuinely helpful.

Complete and Runnable Examples

Never show partial code that won't work in isolation. Users should be able to copy your example and see it work immediately.

❌ Incomplete
// Don't do this - missing imports and setup
const user = await getUser(userId);
updateProfile(user.id, { name: 'John' });
✅ Complete
// Do this - everything needed to run
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function updateUserProfile(userId, updates) {
    try {
        const user = await prisma.user.findUnique({
            where: { id: userId }
        });
        
        if (!user) {
            throw new Error(`User with ID ${userId} not found`);
        }
        
        const updatedUser = await prisma.user.update({
            where: { id: userId },
            data: updates
        });
        
        return updatedUser;
    } catch (error) {
        console.error('Failed to update user:', error);
        throw error;
    }
}

// Usage
const result = await updateUserProfile('user_123', { name: 'John Doe' });

Error Handling That Teaches

Show realistic error handling, not just the happy path. This teaches users about edge cases and builds more robust applications.

Include examples of what happens when things go wrong.

async function fetchUserData(apiKey, userId) {
    if (!apiKey) {
        throw new Error('API key is required');
    }
    
    if (!userId) {
        throw new Error('User ID is required');
    }
    
    try {
        const response = await fetch(`/api/users/${userId}`, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });
        
        // Handle different HTTP status codes
        if (response.status === 401) {
            throw new Error('Invalid API key');
        }
        
        if (response.status === 404) {
            throw new Error('User not found');
        }
        
        if (!response.ok) {
            throw new Error(`HTTP error: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        if (error.name === 'TypeError') {
            throw new Error('Network error - check your connection');
        }
        throw error; // Re-throw other errors
    }
}

Show users how to handle errors gracefully in their applications.

Include retry logic, fallback values, and user-friendly error messages.

Realistic Data and Variables

Use meaningful variable names and realistic data that helps users understand the context.

// Generic, unhelpful names
const data = await api.get('/endpoint');
const result = transform(data.items);
const output = process(result);
// Descriptive, contextual names
const customerOrders = await orderApi.getOrders({
    customerId: 'cust_12345',
    status: 'pending',
    limit: 50
});

const formattedOrders = customerOrders.map(order => ({
    id: order.id,
    total: formatCurrency(order.totalAmount),
    itemCount: order.items.length,
    estimatedDelivery: formatDate(order.estimatedDelivery)
}));

const orderSummary = generateOrderSummary(formattedOrders);

Expected Outputs and Results

Always show users what they should expect to see when running your code.

Example Request:

curl -X POST 'https://api.example.com/v1/customers' \
  -H 'Authorization: Bearer sk_test_123...' \
  -H 'Content-Type: application/json' \
  -d '{
    "email": "sarah@example.com",
    "name": "Sarah Chen",
    "metadata": {
      "source": "documentation_example"
    }
  }'

Expected Response:

{
  "id": "cust_ABcd1234efgh5678",
  "email": "sarah@example.com",
  "name": "Sarah Chen",
  "created": 1699123456,
  "metadata": {
    "source": "documentation_example"
  },
  "default_source": null,
  "subscriptions": {
    "object": "list",
    "data": [],
    "has_more": false,
    "total_count": 0
  }
}

Language-Specific Best Practices

When showing multi-language examples, ensure each follows that language's conventions.

JavaScript
// Use modern JavaScript features
const createUser = async ({ email, name, role = 'user' }) => {
    const userData = {
        email,
        name,
        role,
        createdAt: new Date().toISOString(),
        id: crypto.randomUUID()
    };
    
    const response = await fetch('/api/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(userData)
    });
    
    if (!response.ok) {
        throw new Error(`Failed to create user: ${response.statusText}`);
    }
    
    return response.json();
};
Python
# Use Python conventions and type hints
from typing import Optional, Dict, Any
import requests
import uuid
from datetime import datetime

def create_user(
    email: str, 
    name: str, 
    role: str = "user"
) -> Dict[str, Any]:
    """Create a new user with the provided information."""
    user_data = {
        "email": email,
        "name": name,
        "role": role,
        "created_at": datetime.utcnow().isoformat(),
        "id": str(uuid.uuid4())
    }
    
    try:
        response = requests.post(
            "/api/users",
            json=user_data,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        response.raise_for_status()
        return response.json()
    
    except requests.exceptions.RequestException as e:
        raise RuntimeError(f"Failed to create user: {e}")
Go
// Use Go conventions and proper error handling
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type User struct {
    ID        string    `json:"id"`
    Email     string    `json:"email"`
    Name      string    `json:"name"`
    Role      string    `json:"role"`
    CreatedAt time.Time `json:"created_at"`
}

func CreateUser(email, name, role string) (*User, error) {
    if role == "" {
        role = "user"
    }
    
    user := User{
        Email:     email,
        Name:      name,
        Role:      role,
        CreatedAt: time.Now().UTC(),
    }
    
    jsonData, err := json.Marshal(user)
    if err != nil {
        return nil, fmt.Errorf("failed to marshal user data: %w", err)
    }
    
    resp, err := http.Post(
        "/api/users",
        "application/json",
        bytes.NewBuffer(jsonData),
    )
    if err != nil {
        return nil, fmt.Errorf("failed to send request: %w", err)
    }
    defer resp.Body.Close()
    
    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("request failed with status: %s", resp.Status)
    }
    
    var createdUser User
    if err := json.NewDecoder(resp.Body).Decode(&createdUser); err != nil {
        return nil, fmt.Errorf("failed to decode response: %w", err)
    }
    
    return &createdUser, nil
}

Testing Your Examples

Before publishing, verify every code example works exactly as shown.

Broken code examples destroy user trust faster than missing documentation. Always test before publishing.

Great code examples turn confused users into successful ones. Invest the time to make them excellent.

How is this guide?

Last updated on

Powered by Holocron

Documentation