# Prompt: Write Code Comments

Use this prompt template when you need to add inline code comments to explain complex or non-obvious logic.

## Context

**Project:** [PROJECT_NAME]
**File(s):** [LIST_OF_FILES]
**Language:** [PROGRAMMING_LANGUAGE]

## Goal

Add clear, concise inline comments to explain:
- Complex algorithms or business logic
- Non-obvious implementation decisions
- Workarounds or edge cases
- Performance optimizations
- Security considerations
- Why code does something (not what it does)

## Current Code

```[LANGUAGE]
[PASTE_CODE_THAT_NEEDS_COMMENTS_HERE]
```

## Requirements

**Good comments explain WHY, not WHAT:**

✅ **Good:**
```python
# Retry with exponential backoff to handle transient network errors
# that commonly occur during high-traffic periods
for attempt in range(5):
    delay = 2 ** attempt
    ...
```

❌ **Bad:**
```python
# Loop 5 times
for attempt in range(5):
    # Set delay to 2 to the power of attempt
    delay = 2 ** attempt
    ...
```

**When to add comments:**

- [ ] Complex algorithms (explain the approach)
- [ ] Business logic (explain the requirements)
- [ ] Non-obvious optimizations (explain the trade-off)
- [ ] Workarounds (explain why needed and when to remove)
- [ ] Edge cases (explain the scenario)
- [ ] Security considerations (explain the threat)
- [ ] Performance critical sections (explain the impact)
- [ ] TODO/FIXME markers (with context and ticket number)

**When NOT to add comments:**

- ❌ Self-explanatory code (rename variables instead)
- ❌ Obvious logic (comment would be redundant)
- ❌ Restating what code does (use better naming)
- ❌ Out-of-date or incorrect comments (fix or remove)

**Comment style:**

Follow language-specific conventions:

**Python:**
```python
# Single line comment

# Multi-line comment explaining
# a longer concept that spans
# multiple lines
```

**JavaScript/TypeScript:**
```javascript
// Single line comment

/*
 * Multi-line comment explaining
 * a longer concept
 */
```

**Go:**
```go
// Single line comment

// Multi-line comment explaining
// a longer concept (Go prefers multiple single-line comments)
```

**Rust:**
```rust
// Single line comment

/// Documentation comment for items
/// (use for public APIs)

//! Module-level documentation
```

## Output Format

Provide the code with added comments. Include:

1. **Summary** (list of comments added and why)
2. **Updated code** (complete section with comments)
3. **Notes** (any additional context or suggestions)

## Examples

### Example 1: Complex Algorithm

**Before:**
```python
def fibonacci(n):
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b
```

**After:**
```python
def fibonacci(n):
    """Calculate nth Fibonacci number using iterative approach.

    Uses iteration instead of recursion to avoid stack overflow
    for large n values and improve performance (O(n) time, O(1) space).
    """
    if n <= 1:
        return n

    # Initialize first two Fibonacci numbers
    a, b = 0, 1

    # Calculate iteratively to avoid recursion overhead
    # This approach handles n up to millions without stack overflow
    for _ in range(2, n + 1):
        a, b = b, a + b

    return b
```

### Example 2: Business Logic

**Before:**
```python
def calculate_discount(user, cart_total):
    if user.is_premium and cart_total > 100:
        return cart_total * 0.15
    elif cart_total > 50:
        return cart_total * 0.10
    return 0
```

**After:**
```python
def calculate_discount(user, cart_total):
    """Calculate discount based on user tier and cart total.

    Business rules (updated 2025-01-07):
    - Premium users get 15% off orders over $100
    - All users get 10% off orders over $50
    - Discounts are mutually exclusive (highest applies)
    """
    # Premium tier: 15% discount on orders over $100
    # This incentivizes premium subscriptions and larger orders
    if user.is_premium and cart_total > 100:
        return cart_total * 0.15

    # Standard tier: 10% discount on orders over $50
    # Encourages users to increase cart size to reach threshold
    elif cart_total > 50:
        return cart_total * 0.10

    # No discount for orders under $50
    return 0
```

### Example 3: Workaround

**Before:**
```python
def process_data(data):
    time.sleep(0.1)
    result = expensive_operation(data)
    return result
```

**After:**
```python
def process_data(data):
    """Process data with workaround for upstream API rate limiting.

    WORKAROUND: Sleep 100ms to avoid hitting rate limit.
    Remove when upstream API implements proper rate limiting headers.
    Tracked in: JIRA-1234
    """
    # TODO(JIRA-1234): Replace with proper rate limit handling
    # when upstream API returns Retry-After headers (planned Q2 2025)
    time.sleep(0.1)

    result = expensive_operation(data)
    return result
```

### Example 4: Security Consideration

**Before:**
```python
def hash_password(password):
    salt = os.urandom(32)
    key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
    return salt + key
```

**After:**
```python
def hash_password(password):
    """Hash password using PBKDF2-HMAC-SHA256 with random salt.

    Security notes:
    - Uses cryptographically secure random salt (os.urandom)
    - 100,000 iterations slows down brute-force attacks
    - Salt is prepended to hash for storage (first 32 bytes)
    - Complies with OWASP password storage guidelines
    """
    # Generate 256-bit (32-byte) cryptographically secure random salt
    # Each password gets unique salt to prevent rainbow table attacks
    salt = os.urandom(32)

    # PBKDF2-HMAC-SHA256 with 100,000 iterations
    # High iteration count makes brute-force attacks computationally expensive
    # NIST recommends 100,000+ iterations for PBKDF2 as of 2023
    key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)

    # Store salt + hash together (salt is first 32 bytes)
    # Salt is not secret, but must be unique per password
    return salt + key
```

### Example 5: Performance Optimization

**Before:**
```python
def find_duplicates(items):
    seen = set()
    duplicates = []
    for item in items:
        if item in seen:
            duplicates.append(item)
        else:
            seen.add(item)
    return duplicates
```

**After:**
```python
def find_duplicates(items):
    """Find duplicate items in list using set for O(n) performance.

    Performance characteristics:
    - Time: O(n) - single pass through items
    - Space: O(n) - stores unique items in set

    Alternative approaches considered:
    - Nested loops: O(n²) time, too slow for large lists
    - Sorting first: O(n log n) time, modifies input order
    - Counter: O(n) time but uses more memory
    """
    # Track seen items using set for O(1) lookup
    # Set operations are much faster than list.index() or nested loops
    seen = set()
    duplicates = []

    for item in items:
        # Check membership in O(1) time
        if item in seen:
            duplicates.append(item)
        else:
            # Add to set for future lookups
            seen.add(item)

    return duplicates
```

### Example 6: Edge Cases

**Before:**
```python
def divide(a, b):
    if b == 0:
        return None
    return a / b
```

**After:**
```python
def divide(a, b):
    """Safely divide two numbers with zero-division handling.

    Edge cases handled:
    - Division by zero: Returns None (caller should check)
    - Float division: Always returns float (3/2 = 1.5)
    - Negative numbers: Standard division rules apply
    """
    # Handle division by zero edge case
    # Returning None instead of raising exception allows caller
    # to decide how to handle this case (e.g., default value)
    if b == 0:
        return None

    # Use float division (/) not integer division (//)
    # This ensures consistent behavior: 3/2 = 1.5, not 1
    return a / b
```

## Task

Please add inline comments to the code provided above. Focus on:

1. Explaining WHY the code does something, not WHAT it does
2. Documenting complex algorithms and business logic
3. Highlighting edge cases and security considerations
4. Explaining performance trade-offs
5. Marking TODOs/workarounds with context

**Avoid:**
- Commenting obvious code
- Restating what the code does
- Adding noise without value

## Related Prompts

- **Docstrings**: `prompts/documentation/add-docstrings.md` (for function/class documentation)
- **API docs**: `prompts/documentation/update-api-docs.md` (for external documentation)
- **README**: `prompts/documentation/update-readme.md` (for user-facing docs)
- **PR description**: `prompts/documentation/write-pr-description.md`

## Related Documentation

- **Playbook**: `playbooks/updating-documentation.md`
- **Knowledge base**: `.claude/knowledge/documentation/keeping-docs-updated.md`
- **Engineering standards**: `.claude/standards/ENGINEERING_STANDARDS.md#inline-documentation`
- **Rule #11**: `.claude/standards/CLAUDE_CODE_RULES.md#11-documentation-updates`

## Notes

**When to use docstrings vs. comments:**

- **Docstrings**: Public APIs, function/class documentation, parameters, returns
- **Comments**: Internal logic, edge cases, performance notes, TODOs

**Good comment density:**
- Simple code: 0-5% lines are comments
- Complex code: 10-20% lines are comments
- Security/critical code: 20-30% lines are comments

**Comment maintenance:**
- Update comments when code changes
- Remove outdated comments immediately
- Prefer self-documenting code over excessive comments
