Token导航 LogoToken导航TokenDH.com
开发规范敏感数据github未标认证来源可访问许可证需确认审计通过

code-example-best-practices代码示例最佳实践

Agent Skill

code-example-best-practices 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

240

周安装

10

GitHub Stars

7

下载量

80
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:code-example-best-practices(代码示例最佳实践)
来源仓库:https://github.com/arustydev/ai
仓库路径:skills/code-example-best-practices
安装命令:
npx skills add https://github.com/arustydev/ai --skill code-example-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/arustydev/ai --skill code-example-best-practices

简介

code-example-best-practices 规范技术博客中代码示例的格式、结构和注释标准。

  • 它强调易复制、上下文清晰和错误处理示范,提升示例实用性和教学价值。
  • 适用于文档写作辅助,但不涵盖 prose 风格或整体文章结构设计。
  • 使用前应明确目标读者水平,否则可能生成过于简单或复杂的示例造成理解障碍。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Code Example Best Practices

Guidelines for writing clear, effective code examples in technical blog posts.

Overview

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:

  • Code snippet formatting and structure
  • Comment and annotation guidelines
  • Context and setup requirements
  • Error handling in examples

This skill does NOT cover:

  • Prose writing style (see technical-writing-style)
  • Overall post structure (see content-structure-patterns)

Quick Reference

Code Block Essentials

ElementGuideline
Language tagAlways specify (python, bash, etc.)
LengthUnder 30 lines preferred
WidthUnder 80 characters per line
CommentsExplain "why", not "what"
ImportsInclude when relevant to example

Example Quality Checklist

  • Runs without modification
  • Language tag specified
  • Non-obvious lines commented
  • Variables have meaningful names
  • Sensitive values use placeholders
  • Expected output shown (where helpful)

Principles

1. Make Examples Runnable

Code that doesn't run frustrates readers. Every example should:

  • Include necessary imports
  • Define required variables
  • Use realistic (but safe) placeholder values
  • Work in a standard environment

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())

2. Keep Examples Focused

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

3. Use Progressive Disclosure

For complex examples, build up incrementally:

Step 1: Basic version

def process_data(data):
    return [item.upper() for item in data]

Step 2: Add error handling

def process_data(data):
    results = []
    for item in data:
        try:
            results.append(item.upper())
        except AttributeError:
            results.append(str(item).upper())
    return results

Step 3: Add logging (optional)

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

4. Show Expected Output

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'

Formatting Standards

Language Tags

Always specify the language for syntax highlighting:

def example(): pass

Common tags: python, javascript, typescript, bash, json, yaml, sql, go, rust

Line Length

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)

Comments

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

Placeholder Values

Use obvious placeholders that won't accidentally work:

TypeGood PlaceholderBad Placeholder
API keysyour-api-key-hereabc123
URLshttps://api.example.comhttps://api.com
Passwords<your-password>password123
Emailsuser@example.comtest@test.com
IDs12345 or <user-id>1

Diffs and Changes

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

Common Patterns

Configuration Examples

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")

Command Line Examples

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

Multi-File Examples

When showing multiple files, use clear headers:

src/config.py

DATABASE_URL = "postgres://localhost/mydb"

src/main.py

from config import DATABASE_URL

Error Examples

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'

Anti-Patterns

Screenshot of Code

Never use images for code. Always use text that readers can copy.

Untested Examples

Run every example before publishing. Typos and API changes break tutorials.

Missing Context

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")

Hardcoded Secrets

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"]

See Also

  • technical-writing-style skill - Writing prose around code
  • content-structure-patterns skill - Where code fits in post structure

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.61%
按下载量换算28

Claude

29.89%
按下载量换算24

Cursor

19.01%
按下载量换算15

Gemini CLI

9.89%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills