Code Commenting Prompt Templates

AI prompt templates for writing code comments. Create clear, useful documentation inline.

Overview

Good comments explain why, not what, the code already shows what it does. These prompts help you write comments that add real value: explaining business logic, documenting non-obvious decisions, and warning about gotchas. The goal is comments that help future developers (including yourself) understand and maintain the code.

Best Practices

1

Share the context around the code, comments should explain business rules and design decisions

2

Specify your documentation style (JSDoc, docstrings, etc.) for consistent output

3

Indicate what level of detail you need, file headers vs. inline comments vs. function docs

4

Mention any domain-specific terminology that needs explanation

5

Ask for comments that explain WHY, not WHAT, the code shows what it does

Prompt Templates

1. Function Documentation

Write documentation for this function:

```[LANGUAGE]
[PASTE FUNCTION]
```

**Context:**
- Part of: [MODULE/CLASS]
- Called by: [WHAT USES THIS]
- Business purpose: [WHY IT EXISTS]

**Documentation format:** [JSDOC / PYTHON DOCSTRING / JAVADOC / etc.]

**Include:**
- Brief description
- Parameter descriptions with types and constraints
- Return value description
- Possible exceptions/errors
- Usage example (if complex)
- Any non-obvious behavior or side effects
Language: TypeScript
Function: calculateShippingCost that determines shipping based on weight, destination, and shipping speed
Context: Part of checkout module, called by OrderService
Business purpose: Determines shipping cost for customer orders
Format: JSDoc
```typescript
/**
 * Calculates shipping cost based on package weight, destination, and delivery speed.
 * 
 * Uses tiered pricing: base rate + weight surcharge + speed multiplier.
 * Free shipping is applied for orders over $75 to continental US.
 * 
 * @param weight - Package weight in pounds. Must be positive.
 * @param destination - Shipping destination.
 * @param destination.country - ISO 3166-1 alpha-2 country code (e.g. 'US', 'CA').
 * @param destination.state - State/province code. Required for US/CA.
 * @param destination.isResidential - Residential addresses incur $3 surcharge.
 * @param speed - Delivery speed option.
 * @param orderTotal - Order subtotal in dollars. Used for free shipping calculation.
 * 
 * @returns Shipping cost in dollars, rounded to 2 decimal places.
 * 
 * @throws {InvalidWeightError} If weight is zero or negative.
 * @throws {UnsupportedDestinationError} If country is not in our shipping zones.
 * 
 * @example
 * // Standard shipping to California
 * calculateShippingCost(2.5, { country: 'US', state: 'CA', isResidential: true }, 'standard', 50)
 * // Returns: 8.99
 * 
 * @example
 * // Free shipping for large orders
 * calculateShippingCost(2.5, { country: 'US', state: 'CA', isResidential: false }, 'standard', 100)
 * // Returns: 0 (order > $75 threshold)
 * 
 * @see ShippingZone for zone definitions and rate tables.
 * @see FREE_SHIPPING_THRESHOLD for current free shipping minimum.
 */
function calculateShippingCost(
 weight: number,
 destination: ShippingDestination,
 speed: ShippingSpeed,
 orderTotal: number
): number {
 //...
}
```

When documenting public APIs, complex functions, or functions that other developers will call

  • Include examples for functions with multiple parameters or non-obvious behavior
  • Document edge cases and constraints that aren't obvious from the type signature

2. Inline Comment Generator

Add meaningful inline comments to this code:

```[LANGUAGE]
[PASTE CODE]
```

**What this code does:** [BRIEF DESCRIPTION]
**Business context:** [WHY IT'S NEEDED]

**Comment guidelines:**
- DON'T comment obvious things (// increment i)
- DO explain: business logic, workarounds, algorithms, gotchas
- Highlight: assumptions, TODOs, magic numbers, non-obvious dependencies

**Style:** [BRIEF / MODERATE / DETAILED]

Return the code with appropriate comments added.
Language: Python
Code: Function that processes customer refunds with various conditions
Business context: Refund policy allows full refund within 30 days, partial after, none after 90 days
Style: Moderate
```python
def process_refund(order, requested_amount):
 """
 Process a refund request according to company refund policy.
 
 Policy: Full refund within 30 days, 50% within 90 days, none after.
 """
 days_since_purchase = (datetime.now() - order.created_at).days
 
 # Refund policy thresholds (defined in company policy doc REF-2024-01)
 FULL_REFUND_WINDOW = 30
 PARTIAL_REFUND_WINDOW = 90
 PARTIAL_REFUND_RATE = 0.50
 
 # Orders with chargebacks are handled separately by finance team
 if order.has_chargeback:
 raise RefundBlockedError(
 "Order has chargeback - contact finance@company.com"
 )
 
 # Digital products are non-refundable after download
 # (per Terms of Service section 4.2)
 if order.is_digital and order.was_downloaded:
 raise RefundBlockedError("Digital products cannot be refunded after download")
 
 # Calculate maximum refundable amount based on time window
 if days_since_purchase <= FULL_REFUND_WINDOW:
 max_refund = order.total
 elif days_since_purchase <= PARTIAL_REFUND_WINDOW:
 max_refund = order.total * PARTIAL_REFUND_RATE
 else:
 # Outside refund window - log for customer service metrics
 logger.info(f"Refund denied: order {order.id} is {days_since_purchase} days old")
 raise RefundWindowExpiredError(f"Refunds not available after {PARTIAL_REFUND_WINDOW} days")
 
 # Customer can request less than max (e.g. partial item return)
 refund_amount = min(requested_amount, max_refund)
 
 # IMPORTANT: Refund to original payment method only
 # Stripe requires original charge ID for refunds
 if not order.stripe_charge_id:
 raise RefundError("Cannot process refund: missing payment reference")
 
 # Process the actual refund through Stripe
 # This is idempotent - Stripe dedupes by our refund_id
 stripe_refund = stripe.Refund.create(
 charge=order.stripe_charge_id,
 amount=int(refund_amount * 100), # Stripe expects cents
 metadata={'order_id': order.id, 'reason': 'customer_request'}
 )
 
 return RefundResult(
 amount=refund_amount,
 stripe_refund_id=stripe_refund.id,
 was_partial=(refund_amount < order.total)
 )
```

When making code clearer for future maintainers, documenting complex business logic, or onboarding new team members

  • Reference external documents (policies, specs) when business rules aren't self-explanatory
  • Mark temporary code or workarounds with TODO and a ticket number

3. File/Module Header

Write a file header comment for this module:

**File:** [FILENAME]
**Purpose:** [WHAT THIS FILE/MODULE DOES]

**Key contents:**
- [CLASS/FUNCTION 1]
- [CLASS/FUNCTION 2]

**Dependencies:** [WHAT IT DEPENDS ON]
**Used by:** [WHAT USES THIS MODULE]

**Format:** [YOUR HEADER STYLE]

**Include:**
- Brief overview
- Key concepts/terminology
- Usage notes if any
- Author/maintainer (optional)
File: payment_processor.py
Purpose: Handles all payment processing logic including charges, refunds, and subscriptions
Key contents: PaymentProcessor class, CardValidator, SubscriptionManager
Dependencies: Stripe API, customer database
Used by: Checkout service, subscription renewal jobs, admin panel
```python
"""
Payment Processing Module
=========================

Centralized payment handling for all monetary transactions. Integrates with
Stripe for card processing and manages the full payment lifecycle.

Key Components:
 PaymentProcessor: Main class for one-time charges and refunds.
 SubscriptionManager: Handles recurring billing and plan changes.
 CardValidator: Pre-validates card details before submission.

Usage:
 from payments.payment_processor import PaymentProcessor
 
 processor = PaymentProcessor()
 result = processor.charge(amount=1999, customer_id='cust_123')

Configuration:
 Requires STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET environment variables.
 See config/payments.py for additional settings.

Error Handling:
 All payment operations raise PaymentError subclasses:
 - CardDeclinedError: Card was declined
 - InsufficientFundsError: Not enough balance
 - PaymentProcessingError: Stripe API issues

Internal Dependencies:
 - models.customer: Customer records and payment methods
 - services.notifications: Payment confirmation emails

External Dependencies:
 - Stripe API v2023-10-16

See Also:
 - docs/payments.md: Full payment flow documentation
 - Stripe Dashboard: https://dashboard.stripe.com

Maintainers: payments-team@company.com
"""
```

When creating new modules, documenting existing modules, or establishing documentation standards

  • File headers should help developers decide if this is the file they're looking for
  • Include 'See Also' links to related documentation or dashboards

4. TODO/FIXME Comment Generator

Generate appropriate TODO/FIXME comments for these issues in the code:

```[LANGUAGE]
[PASTE CODE]
```

**Known issues:**
- [ISSUE 1]
- [ISSUE 2]
- [ISSUE 3]

**TODO format:** [YOUR TEAM'S FORMAT - e.g. TODO(username): or TODO #TICKET:]

**For each issue, create a comment that includes:**
- What needs to be done
- Why it's needed
- When/what would trigger fixing it
- Any relevant ticket/issue numbers
Language: JavaScript
Code: Authentication middleware
Issues:
1. Token refresh logic has a race condition under high concurrency
2. We're using deprecated crypto method that needs updating
3. Error messages expose internal details, should be generic in production
Format: TODO(team/person): description #TICKET
```javascript
function authenticateRequest(req, res, next) {
 const token = req.headers.authorization?.split(' ')[1];
 
 if (!token) {
 // TODO(security): Generic message in prod, detailed in dev #SEC-234
 // Currently exposes that auth is token-based. Should just say "Unauthorized"
 // in production while keeping detailed errors for development debugging.
 return res.status(401).json({ error: 'No authentication token provided' });
 }
 
 try {
 // FIXME(platform): Replace deprecated crypto.createCipher #TECH-567
 // Node.js 18 removes createCipher entirely. Need to migrate to
 // createCipheriv with explicit IV before upgrading Node version.
 // Migration guide: https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
 const decoded = verifyToken(token);
 
 // TODO(auth): Fix race condition in token refresh #AUTH-891
 // When multiple requests arrive with an about-to-expire token,
 // they can all trigger refresh simultaneously, invalidating each other.
 // Proposed fix: Use Redis lock or accept-both-tokens window.
 // Affects: ~0.1% of requests during token refresh window.
 if (isTokenExpiringSoon(decoded)) {
 const newToken = refreshToken(decoded);
 res.setHeader('X-New-Token', newToken);
 }
 
 req.user = decoded;
 next();
 } catch (error) {
 // TODO(security): Sanitize error messages for production #SEC-234
 // Don't expose "Invalid signature" vs "Token expired" difference
 // to potential attackers. Log detailed error server-side only.
 logger.warn('Auth failed', { error: error.message, token: token.slice(0, 10) + '...' });
 return res.status(401).json({ error: error.message });
 }
}
```

### TODO Summary for Tracking

| Priority | Ticket | Issue | Trigger |
|----------|--------|-------|--------|
| High | SEC-234 | Error message exposure | Security audit |
| High | TECH-567 | Deprecated crypto | Before Node 18 upgrade |
| Medium | AUTH-891 | Token refresh race condition | If user complaints increase |

When documenting technical debt, known issues, or planned improvements

  • Always include a ticket number, TODOs without tickets rarely get done
  • Add 'Trigger' to indicate when the TODO becomes urgent

Common Mistakes to Avoid

Commenting WHAT the code does instead of WHY, '// increment counter' adds no value

Writing comments that get out of sync with code, stale comments are worse than no comments

Over-commenting simple code while leaving complex business logic unexplained

Frequently Asked Questions

Good comments explain why, not what, the code already shows what it does. These prompts help you write comments that add real value: explaining business logic, documenting non-obvious decisions, and warning about gotchas. The goal is comments that help future developers (including yourself) understand and maintain the code.

Related Templates

Have your own prompt to optimize?