Claude
Skills
Sign in
Back

document-code

Included with Lifetime
$97 forever

Generates documentation for code including function/class docstrings, module READMEs, API documentation, inline comments, and architecture overviews. Use when the user says "document this", "add docs", "add comments", "generate README", "what does this code do?", "write API docs", or "this needs documentation".

Backend & APIs

What this skill does


# Document Code Skill

When documenting code, follow this structured process. Good documentation explains WHY, not just WHAT. The code already shows what it does — documentation should explain the intent, context, trade-offs, and gotchas.

## 1. Understand Before Documenting

Before writing any documentation:

- **Read the code thoroughly** — understand the full context
- **Identify the audience** — is this for new team members, API consumers, future maintainers, or yourself?
- **Check existing docs** — don't duplicate or contradict what already exists
- **Understand the architecture** — how does this code fit into the bigger picture?

## 2. Documentation Types

Determine what kind of documentation is needed:

| Type | When to Use |
|------|-------------|
| **Inline comments** | Complex logic, workarounds, non-obvious decisions |
| **Function/method docstrings** | Every public function, method, and class |
| **Module/file headers** | Every file that isn't self-explanatory from its name |
| **README** | Every module, package, or service |
| **API documentation** | Every endpoint consumers interact with |
| **Architecture docs** | System design, data flow, component relationships |
| **Changelog** | Tracking changes between versions |
| **Migration guides** | Breaking changes that require action |

## 3. Inline Comments

### When to Comment
- **Complex algorithms** — explain the approach, not each line
- **Workarounds and hacks** — explain WHY and link to the issue/ticket
- **Non-obvious business rules** — explain the domain logic
- **Performance choices** — explain why a less readable approach was chosen
- **Regex patterns** — always explain what they match
- **Magic numbers** — explain where they come from

### When NOT to Comment
- Don't restate what the code already says
- Don't comment every line
- Don't leave commented-out code (use version control)
- Don't write TODOs without ticket numbers
```
// 🔴 BAD — restates the code
// Set age to 18
const age = 18;

// ✅ GOOD — explains WHY
// Minimum age required by COPPA compliance (Children's Online Privacy Protection Act)
const MINIMUM_AGE = 18;

// 🔴 BAD — vague TODO
// TODO: fix this later

// ✅ GOOD — actionable TODO
// TODO(JIRA-1234): Replace with batch query once the ORM supports it. Current N+1
// causes ~200ms latency on pages with 50+ items.

// ✅ GOOD — explains a workaround
// HACK: Safari doesn't support the CSS gap property in flex containers on iOS < 14.5.
// Using margin-based spacing instead. Remove when we drop iOS 14 support.
// See: https://bugs.webkit.org/show_bug.cgi?id=XXXXX

// ✅ GOOD — explains regex
// Matches email addresses: [email protected]
// Allows: letters, numbers, dots, hyphens, underscores in local part
// Requires: at least one dot in domain, 2-63 char TLD
const EMAIL_REGEX = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/;
```

## 4. Function & Method Documentation

Every public function should document:
- **What it does** — one-line summary
- **Parameters** — name, type, description, constraints, defaults
- **Return value** — type, description, possible values
- **Errors/exceptions** — what can go wrong and when
- **Examples** — at least one usage example for non-trivial functions
- **Side effects** — database writes, API calls, file changes, event emissions

## 5. Stack-Specific Docstring Formats

### TypeScript / JavaScript (TSDoc / JSDoc)
```typescript
/**
 * Calculates the shipping cost for an order based on weight, destination, and shipping method.
 *
 * Uses the carrier's rate table for standard/express and falls back to flat-rate
 * pricing for international destinations not in the rate table.
 *
 * @param order - The order containing items with weight and dimensions
 * @param destination - Shipping address with country and postal code
 * @param method - Shipping method: 'standard' (5-7 days), 'express' (1-2 days), or 'overnight'
 * @returns The calculated shipping cost in cents (USD). Returns 0 for orders over $100 (free shipping promo)
 * @throws {InvalidAddressError} If the destination address cannot be validated
 * @throws {CarrierUnavailableError} If no carrier supports the destination country
 *
 * @example
 * const cost = await calculateShipping(order, { country: 'US', postal: '90210' }, 'standard');
 * // Returns: 599 (i.e., $5.99)
 *
 * @see {@link ShippingRateTable} for carrier rate configuration
 * @since 2.1.0
 */
async function calculateShipping(
  order: Order,
  destination: Address,
  method: ShippingMethod
): Promise<number> { ... }
```

### TypeScript Interfaces and Types
```typescript
/**
 * Represents a user account in the system.
 *
 * Created during registration and updated via the profile settings page.
 * Soft-deleted when the user requests account deletion (retained for 30 days per compliance policy).
 */
interface User {
  /** Unique identifier (UUIDv4), generated at creation */
  id: string;

  /** User's email address, used for login. Must be unique and verified. */
  email: string;

  /** Display name shown in the UI. 2-50 characters, no special characters. */
  name: string;

  /**
   * User's role determining access level.
   * - 'viewer': Read-only access to shared resources
   * - 'editor': Can create and modify own resources
   * - 'admin': Full access including user management
   */
  role: 'viewer' | 'editor' | 'admin';

  /** ISO 8601 timestamp of account creation */
  createdAt: string;

  /** ISO 8601 timestamp of last login, null if never logged in */
  lastLoginAt: string | null;
}
```

### Python (Google Style Docstrings)
```python
def calculate_shipping(order: Order, destination: Address, method: str = "standard") -> int:
    """Calculate shipping cost for an order based on weight and destination.

    Uses the carrier's rate table for domestic shipments and falls back
    to flat-rate pricing for international destinations not in the rate table.

    Args:
        order: The order containing items with weight and dimensions.
        destination: Shipping address with country and postal code.
        method: Shipping method. One of 'standard' (5-7 days),
            'express' (1-2 days), or 'overnight'. Defaults to 'standard'.

    Returns:
        Shipping cost in cents (USD). Returns 0 for orders over $100
        due to the free shipping promotion.

    Raises:
        InvalidAddressError: If the destination address cannot be validated
            against the carrier's address database.
        CarrierUnavailableError: If no carrier supports the destination country.

    Example:
        >>> cost = calculate_shipping(order, Address(country="US", postal="90210"))
        >>> print(cost)
        599  # $5.99

    Note:
        International rates are refreshed daily at midnight UTC from the
        carrier API. Cached rates may be up to 24 hours stale.
    """
```

### Python Classes
```python
class OrderProcessor:
    """Processes orders from cart submission through fulfillment.

    Handles the complete order lifecycle: validation, payment capture,
    inventory reservation, and shipping label generation. Uses the saga
    pattern to ensure all steps complete or roll back atomically.

    Attributes:
        payment_gateway: The payment provider client (Stripe/PayPal).
        inventory_service: Service for checking and reserving stock.
        notification_service: Sends order confirmation emails and SMS.

    Example:
        >>> processor = OrderProcessor(
        ...     payment_gateway=StripeClient(),
        ...     inventory_service=InventoryService(),
        ... )
        >>> result = await processor.process(cart, user)
        >>> print(result.order_id)
        'ord_abc123'

    Note:
        This class is NOT thread-safe. Use one instance per request
        in web applications.
    """
```

### Go (Godoc)
```go
// CalculateShipping returns the shipping cost in cents for the given order.
//
// It uses the carrier's rate table for domestic shipments and falls back
// to flat-rate pricing fo

Related in Backend & APIs