Guidelines for writing effective code examples in technical blog posts
Generates clear, runnable code examples for technical blog posts with proper formatting and annotations.
npx claudepluginhub arustydev/aiThis skill inherits all available tools. When active, it can use any tool Claude has access to.
Guidelines for writing clear, effective code examples in technical blog posts.
Code examples are often the most valuable part of technical content. This skill provides standards for writing code snippets that are easy to understand, copy, and adapt.
This skill covers:
This skill does NOT cover:
| Element | Guideline |
|---|---|
| Language tag | Always specify (python, bash, etc.) |
| Length | Under 30 lines preferred |
| Width | Under 80 characters per line |
| Comments | Explain "why", not "what" |
| Imports | Include when relevant to example |
Code that doesn't run frustrates readers. Every example should:
Good:
import os
from pathlib import Path
# Read config from environment (provide default for local dev)
api_key = os.environ.get("API_KEY", "your-api-key-here")
config_path = Path("config.json")
if config_path.exists():
config = json.loads(config_path.read_text())
Bad:
# Missing imports, undefined variables
config = json.loads(config_path.read_text())
Show only what's necessary. Strip everything else.
Good:
# Retry with exponential backoff
for attempt in range(max_retries):
try:
return make_request(url)
except RequestError:
sleep(2 ** attempt)
raise MaxRetriesExceeded()
Bad:
# Too much context obscures the pattern
import requests
import logging
from typing import Optional
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@dataclass
class Config:
max_retries: int = 3
base_url: str = "https://api.example.com"
timeout: int = 30
def make_request(url: str, config: Optional[Config] = None) -> dict:
config = config or Config()
# ... 20 more lines before getting to the retry logic
For complex examples, build up incrementally:
def process_data(data):
return [item.upper() for item in data]
def process_data(data):
results = []
for item in data:
try:
results.append(item.upper())
except AttributeError:
results.append(str(item).upper())
return results
def process_data(data, logger=None):
results = []
for item in data:
try:
results.append(item.upper())
except AttributeError:
if logger:
logger.warning(f"Converting {type(item)} to string")
results.append(str(item).upper())
return results
Help readers verify they're on track:
$ curl -s https://api.example.com/health | jq
{
"status": "healthy",
"version": "1.2.3"
}
>>> calculate_hash("hello world")
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
Always specify the language for syntax highlighting:
```python
def example():
pass
```
Common tags: python, javascript, typescript, bash, json, yaml, sql, go, rust
Keep lines under 80 characters to prevent horizontal scrolling:
# Good: Line breaks at logical points
result = (
some_long_function_name(
parameter_one=value,
parameter_two=other_value,
)
)
# Avoid: Long lines that scroll
result = some_long_function_name(parameter_one=value, parameter_two=other_value, parameter_three=another_value)
Comment the "why", not the "what":
# Good: Explains reasoning
# Use a set for O(1) lookup on large datasets
seen = set()
# Bad: States the obvious
# Create a set called seen
seen = set()
Inline comments for non-obvious lines:
response = client.get(url, timeout=30) # Server can be slow during peak hours
data = response.json().get("results", []) # API returns empty list as null
Use obvious placeholders that won't accidentally work:
| Type | Good Placeholder | Bad Placeholder |
|---|---|---|
| API keys | your-api-key-here | abc123 |
| URLs | https://api.example.com | https://api.com |
| Passwords | <your-password> | password123 |
| Emails | user@example.com | test@test.com |
| IDs | 12345 or <user-id> | 1 |
Show what changed when modifying code:
def process_data(data):
- return data.upper()
+ return data.strip().upper()
Or use comments to highlight changes:
def process_data(data):
return data.strip().upper() # Added strip() to handle whitespace
Show both environment variables and code:
# Set in your shell or .env file
export DATABASE_URL="postgres://user:pass@localhost:5432/mydb"
export REDIS_URL="redis://localhost:6379"
import os
DATABASE_URL = os.environ["DATABASE_URL"]
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379")
Use $ prefix for commands, show output without prefix:
$ npm install express
added 57 packages in 2.3s
$ npm start
Server running on http://localhost:3000
When showing multiple files, use clear headers:
src/config.py
DATABASE_URL = "postgres://localhost/mydb"
src/main.py
from config import DATABASE_URL
When showing errors, include enough context to diagnose:
>>> import missing_module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'missing_module'
Never use images for code. Always use text that readers can copy.
Run every example before publishing. Typos and API changes break tutorials.
Don't assume readers know the file structure or have run previous steps:
# Bad: Where does 'client' come from?
response = client.get("/users")
# Good: Show the setup
from myapp import create_client
client = create_client(api_key=os.environ["API_KEY"])
response = client.get("/users")
Never include real credentials, even in "example" form:
# NEVER do this
api_key = "sk-live-abc123..." # This looks like a real key
# Do this instead
api_key = os.environ["API_KEY"]
technical-writing-style skill - Writing prose around codecontent-structure-patterns skill - Where code fits in post structureActivates when the user asks about AI prompts, needs prompt templates, wants to search for prompts, or mentions prompts.chat. Use for discovering, retrieving, and improving prompts.
Search, retrieve, and install Agent Skills from the prompts.chat registry using MCP tools. Use when the user asks to find skills, browse skill catalogs, install a skill for Claude, or extend Claude's capabilities with reusable AI agent components.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.