- name
- documentation-writing
- description
- Audience-first documentation guidance for READMEs, API docs, architecture docs, and tutorials. Ensures clarity, completeness, and maintainability.
# Documentation Writing Skill
## Core Principle
**Write for the reader's context, not the author's understanding.**
Documentation exists to transfer knowledge efficiently. Good documentation anticipates questions, provides context, and guides readers to success. The best documentation makes the next user (or future you) productive without requiring tribal knowledge or guesswork.
**Effective documentation:**
- Meets readers where they are (assumes appropriate background)
- Answers "why" not just "what" and "how"
- Provides working examples
- Stays current with code changes
- Guides readers to success, not just describes features
---
## Documentation Types
Different documentation serves different purposes. Choose the right type for your audience and goal.
### README.md (Project Overview)
**Purpose:** First impression and quick-start guide for new users/contributors
**Audience:**
- New users evaluating the project
- Developers wanting to contribute
- Stakeholders assessing project status
**Must include:**
- What the project does (1-2 sentences)
- Why it exists (problem being solved)
- Quick start (minimal steps to see it working)
- Installation/setup instructions
- Basic usage examples
- Link to fuller documentation
- How to contribute (if open source)
- License information
**Template:**
```markdown
# Project Name
Brief description (1-2 sentences) of what this project does.
## Why This Exists
[Problem statement - what pain point does this solve?]
## Quick Start
```bash
# Minimal steps to get running
npm install
npm start
# Now visit http://localhost:3000
```
## Installation
[Detailed setup instructions]
## Usage
[Basic examples with expected output]
## Documentation
- [API Reference](docs/api.md)
- [Architecture Guide](docs/architecture.md)
- [Contributing Guide](CONTRIBUTING.md)
## License
[License type and link]
```
### API Documentation (Reference)
**Purpose:** Technical reference for developers using the API/library
**Audience:** Developers integrating with your code
**Must include:**
- Function/method signatures
- Parameter types and constraints
- Return types and possible values
- Error conditions and exceptions
- Working code examples
- Performance characteristics (if relevant)
**Template:**
```markdown
## functionName(param1, param2, options)
Brief description of what this function does.
**Parameters:**
- `param1` (string, required): Description of parameter
- `param2` (number, optional, default: 0): Description
- `options` (object, optional): Configuration options
- `option1` (boolean, default: false): Description
- `option2` (string, default: 'value'): Description
**Returns:**
- (Promise<Result>): Description of return value
**Throws:**
- `ValidationError`: When param1 is empty
- `NotFoundError`: When resource doesn't exist
**Example:**
```javascript
const result = await functionName('input', 42, {
option1: true
});
console.log(result); // { status: 'success', data: ... }
```
**Performance:**
- Time complexity: O(n)
- Caches results for 5 minutes
```
### Architecture Documentation (Design)
**Purpose:** Explain system design, patterns, and decisions
**Audience:**
- New team members ramping up
- Developers making changes
- Technical stakeholders reviewing design
**Must include:**
- System overview (components and interactions)
- Key design decisions and rationale
- Data flow diagrams
- Technology choices and tradeoffs
- Scaling considerations
- Security model
- Known limitations
**Template:**
```markdown
# System Architecture
## Overview
[High-level description of system components]
```
[ASCII diagram or mermaid diagram showing components]
User → API Gateway → Service Layer → Database
↓
Cache Layer
```
## Components
### Component Name
**Purpose:** What this component does
**Technology:** What it's built with
**Interactions:** What it talks to and how
**Scalability:** How it scales
## Design Decisions
### Decision: Why We Chose Technology X
**Context:** What problem we were solving
**Options Considered:** A, B, C
**Decision:** We chose B
**Rationale:** Why B was better than A and C
**Consequences:** Tradeoffs we accepted
## Data Flow
[Description of how data moves through the system]
## Security Model
[Authentication, authorization, encryption, etc.]
## Known Limitations
[Current constraints and future improvements]
```
### Tutorial (Learning)
**Purpose:** Teach users how to accomplish specific goals
**Audience:** Users learning to use the system
**Must include:**
- Clear learning objective
- Prerequisites (assumed knowledge)
- Step-by-step instructions
- Expected output at each step
- Explanations of what's happening
- Common mistakes and troubleshooting
- Next steps for further learning
**Template:**
```markdown
# Tutorial: [Learning Objective]
In this tutorial, you'll learn how to [specific goal]. By the end, you'll be
able to [concrete outcome].
## Prerequisites
Before starting, you should:
- Have [software] installed
- Understand [concepts]
- Have completed [prior tutorial]
## Step 1: [First Action]
[Detailed instruction]
```bash
command to run
```
**What's happening:** [Explanation of what this step does and why]
**Expected output:**
```
output you should see
```
**Troubleshooting:**
- If you see error X, do Y
- If Z doesn't work, check A
## Step 2: [Next Action]
[Continue pattern...]
## What You Learned
- Concept 1
- Concept 2
- How to do X
## Next Steps
- Try [related tutorial]
- Read [reference docs]
- Build [practice project]
```
### Reference Documentation (Lookup)
**Purpose:** Quick lookup for specific information
**Audience:** Users who know what they're looking for
**Must include:**
- Organized by category
- Searchable/indexable structure
- Concise descriptions
- Links to related information
- Version-specific information
**Template:**
```markdown
# Configuration Reference
## Environment Variables
### DATABASE_URL
- **Type:** String (connection string)
- **Required:** Yes
- **Default:** None
- **Example:** `postgresql://user:pass@localhost:5432/dbname`
- **Description:** Database connection string for PostgreSQL
### LOG_LEVEL
- **Type:** String (debug|info|warn|error)
- **Required:** No
- **Default:** `info`
- **Example:** `LOG_LEVEL=debug`
- **Description:** Logging verbosity level
## Configuration File
[Similar structure for config file options]
## See Also
- [Deployment Guide](deployment.md)
- [Troubleshooting](troubleshooting.md)
```
---
## Writing Style Guide
### Clarity Principles
**Use active voice:**
- ✅ "The function returns a promise"
- ❌ "A promise is returned by the function"
**Be specific:**
- ✅ "Install Node.js 18.x or later"
- ❌ "Install a recent version of Node.js"
**Use consistent terminology:**
- Choose one term and stick with it (user/customer, config/configuration)
- Don't switch between synonyms
- Define domain-specific terms
**Keep sentences short:**
- One idea per sentence
- Break complex sentences into multiple simple ones
- Use bullets for lists
### Example-Driven Writing
**Always provide examples:**
Bad (no example):
```markdown
The API accepts JSON payloads with user data.
```
Good (with example):
```markdown
The API accepts JSON payloads with user data:
```json
{
"name": "Jane Doe",
"email": "jane@example.com",
"role": "admin"
}
```
```
**Show both success and failure cases:**
```markdown
**Success response:**
```json
{ "status": "ok", "userId": 123 }
```
**Error response:**
```json
{ "status": "error", "message": "Invalid email format" }
```
```
### Audience Awareness
**Adjust complexity to audience:**
For beginners:
```markdown
Run `npm install` to download the project dependencies. Dependencies are
external code libraries that your project needs to function.
```
For experienced developers:
```markdown
Run `npm install` to install dependencies.
```
**Don't condescend:**
- ❌ "Obviously, you should..."
- ❌ "Simply just..."
- ❌ "As everyone knows..."
- ✅ "First, configure the database connection..."
### Consistency Standards
**Use consistent formatting:**
- Code: `backticks`
- Commands: ```bash code blocks```
- File paths: `path/to/file.md`
- Variables: `VARIABLE_NAME`
- UI elements: **Bold**
**Use consistent structure:**
- Same heading levels for similar content
- Same example format throughout
- Same terminology across documents
**Maintain consistent voice:**
- Choose second person ("you") or third person and stick with it
- Maintain same level of formality throughout
- Use same tense (usually present for docs)
---
## Code Integration
Good documentation lives close to the code it describes.
### Docstrings (Function/Class Documentation)
**Python example:**
```python
def calculate_tax(amount: float, rate: float, region: str = 'US') -> float:
"""Calculate tax amount based on rate and region.
Args:
amount: The pre-tax amount in dollars
rate: Tax rate as decimal (0.1 for 10%)
region: Tax region code (default: 'US')
Returns:
Tax amount in dollars, rounded to 2 decimal places
Raises:
ValueError: If amount is negative or rate is outside 0-1 range
Example:
>>> calculate_tax(100.0, 0.1)
10.0
>>> calculate_tax(100.0, 0.2, region='EU')
20.0
"""
if amount < 0:
raise ValueError("Amount cannot be negative")
if not 0 <= rate <= 1:
raise ValueError("Rate must be between 0 and 1")
return round(amount * rate, 2)
```
**JavaScript/TypeScript example:**
```typescript
/**
* Calculate tax amount based on rate and region.
*
* @param amount - The pre-tax amount in dollars
* @param rate - Tax rate as decimal (0.1 for 10%)
* @param region - Tax region code (default: 'US')
* @returns Tax amount in dollars, rounded to 2 decimal places
* @throws {Error} If amount is negative or rate is outside 0-1 range
*
* @example
* ```typescript
* calculateTax(100.0, 0.1) // returns 10.0
* calculateTax(100.0, 0.2, 'EU') // returns 20.0
* ```
*/
function calculateTax(
amount: number,
rate: number,
region: string = 'US'
): number {
if (amount < 0) {
throw new Error('Amount cannot be negative');
}
if (rate < 0 || rate > 1) {
throw new Error('Rate must be between 0 and 1');
}
return Math.round(amount * rate * 100) / 100;
}
```
### Inline Comments
**When to comment:**
- Complex algorithms (explain the approach)
- Non-obvious workarounds (explain why it's necessary)
- Business logic (explain the domain rule)
- Performance optimizations (explain the tradeoff)
**When NOT to comment:**
- Obvious code (the code is self-documenting)
- Repeating function/variable names
- Commented-out code (delete it, git remembers)
**Good comments:**
```python
# Use binary search since data is sorted (O(log n) vs O(n))
index = binary_search(sorted_data, target)
# Retry with exponential backoff per API rate limit docs
for attempt in range(max_retries):
try:
result = api_call()
break
except RateLimitError:
time.sleep(2 ** attempt)
```
**Bad comments:**
```python
# Increment counter
counter = counter + 1
# Loop through items
for item in items:
# Process item
process(item)
```
### Type Hints/Annotations
Type hints serve as inline documentation:
**Python:**
```python
from typing import List, Dict, Optional
def find_users(
filters: Dict[str, str],
limit: int = 10,
offset: int = 0
) -> List[User]:
"""Find users matching filters.
Types document the contract:
- filters: field name -> filter value
- limit/offset: pagination parameters
- returns: list of User objects (never None)
"""
pass
def get_user(user_id: str) -> Optional[User]:
"""Get user by ID, or None if not found."""
pass
```
**TypeScript:**
```typescript
interface User {
id: string;
name: string;
email: string;
Voir sur GitHub