AI 已经彻底改变了软件开发。本章介绍用于代码生成、调试、审查和开发工作流程的提示词技巧。

<Callout type="info" title="AI 作为编程伙伴">
AI 擅长代码生成、调试和文档编写——但务必审查生成的代码，检查安全性、正确性和可维护性。未经测试，切勿部署 AI 生成的代码。
</Callout>

## 代码生成

### 应做与不应做：代码提示词

<Compare 
  before={{ label: "❌ 模糊的请求", content: "写一个验证邮箱的函数。" }}
  after={{ label: "✓ 完整的规格说明", content: "写一个 Python 函数来验证邮箱地址。\n\n输入：string（可能的邮箱地址）\n输出：tuple[bool, str | None] - (is_valid, error_message)\n处理：空字符串、None、unicode 字符\n使用正则表达式，包含类型注解和文档字符串。" }}
/>

### 函数生成

<TryIt compact prompt={`Write a \${language:Python} function that \${description:validates email addresses}.

Requirements:
- Input: \${inputTypes:string (potential email)}
- Output: \${outputType:boolean and optional error message}
- Handle edge cases: \${edgeCases:empty string, None, unicode characters}
- Performance: \${performance:standard}

Include:
- Type hints/annotations
- Docstring with examples
- Input validation
- Error handling`} />

### 类/模块生成

<TryIt compact prompt={`Create a \${language:Python} class for \${purpose:managing user sessions}.

Class design:
- Name: \${className:SessionManager}
- Responsibility: \${responsibility:handle user session lifecycle}
- Properties: \${properties:session_id, user_id, created_at, expires_at}
- Methods: \${methods:create(), validate(), refresh(), destroy()}

Requirements:
- Follow \${designPattern:Singleton} pattern
- Include proper encapsulation
- Add comprehensive docstrings
- Include usage example

Testing:
- Include unit test skeleton`} />

### API 端点生成

<TryIt compact prompt={`Create a REST API endpoint for \${resource:user profiles}.

Framework: \${framework:FastAPI}
Method: \${method:GET}
Path: \${path:/api/users/{id}}

Request:
- Headers: \${headers:Authorization Bearer token}
- Body schema: \${bodySchema:N/A for GET}
- Query params: \${queryParams:include_posts (boolean)}

Response:
- Success: \${successResponse:200 with user object}
- Errors: \${errorResponses:401 Unauthorized, 404 Not Found}

Include:
- Input validation
- Authentication check
- Error handling
- Rate limiting consideration`} />

## 调试

<Callout type="tip" title="调试原则">
始终包含**预期行为**、**实际行为**和**错误信息**（如有）。你提供的上下文越多，AI 就能越快找到根本原因。
</Callout>

### Bug 分析

<TryIt compact prompt={`Debug this code. It should \${expectedBehavior:return the sum of all numbers} but instead \${actualBehavior:returns 0 for all inputs}.

Code:
\${code:paste your code here}

Error message (if any):
\${error:none}

Steps to debug:
1. Identify what the code is trying to do
2. Trace through execution with the given input
3. Find where expected and actual behavior diverge
4. Explain the root cause
5. Provide the fix with explanation`} />

### 错误信息解读

<TryIt compact prompt={`Explain this error and how to fix it:

Error:
\${errorMessage:paste error message or stack trace here}

Context:
- Language/Framework: \${framework:Python 3.11}
- What I was trying to do: \${action:reading a JSON file}
- Relevant code: \${codeSnippet:paste relevant code}

Provide:
1. Plain English explanation of the error
2. Root cause
3. Step-by-step fix
4. How to prevent this in the future`} />

### 性能调试

<TryIt compact prompt={`This code is slow. Analyze and optimize:

Code:
\${code:paste your code here}

Current performance: \${currentPerformance:takes 30 seconds for 1000 items}
Target performance: \${targetPerformance:under 5 seconds}
Constraints: \${constraints:memory limit 512MB}

Provide:
1. Identify bottlenecks
2. Explain why each is slow
3. Suggest optimizations (ranked by impact)
4. Show optimized code
5. Estimate improvement`} />

## 代码审查

### 应做与不应做：代码审查提示词

<Compare 
  before={{ label: "❌ 笼统的请求", content: "审查这段代码。" }}
  after={{ label: "✓ 具体的标准", content: "为 Pull Request 审查这段代码。\n\n检查：\n1. 正确性：bug、逻辑错误、边界情况\n2. 安全性：注入风险、认证问题\n3. 性能：N+1 查询、内存泄漏\n4. 可维护性：命名、复杂度\n\n格式：🔴 严重 / 🟡 重要 / 🟢 建议" }}
/>

### 综合审查

<TryIt compact prompt={`Review this code for a pull request.

Code:
\${code:paste your code here}

Review for:
1. **Correctness**: Bugs, logic errors, edge cases
2. **Security**: Vulnerabilities, injection risks, auth issues
3. **Performance**: Inefficiencies, N+1 queries, memory leaks
4. **Maintainability**: Readability, naming, complexity
5. **Best practices**: \${framework:Python/Django} conventions

Format your review as:
🔴 Critical: must fix before merge
🟡 Important: should fix
🟢 Suggestion: nice to have
💭 Question: clarification needed`} />

### 安全审查

<TryIt compact prompt={`Perform a security review of this code:

Code:
\${code:paste your code here}

Check for:
- [ ] Injection vulnerabilities (SQL, XSS, command)
- [ ] Authentication/authorization flaws
- [ ] Sensitive data exposure
- [ ] Insecure dependencies
- [ ] Cryptographic issues
- [ ] Input validation gaps
- [ ] Error handling that leaks info

For each finding:
- Severity: Critical/High/Medium/Low
- Location: Line number or function
- Issue: Description
- Exploit: How it could be attacked
- Fix: Recommended remediation`} />

## 重构

### 代码异味检测

<TryIt compact prompt={`Analyze this code for code smells and refactoring opportunities:

Code:
\${code:paste your code here}

Identify:
1. Long methods (suggest extraction)
2. Duplicate code (suggest DRY improvements)
3. Complex conditionals (suggest simplification)
4. Poor naming (suggest better names)
5. Tight coupling (suggest decoupling)

For each issue, show before/after code.`} />

### 设计模式应用

<TryIt compact prompt={`Refactor this code using the \${patternName:Factory} pattern.

Current code:
\${code:paste your code here}

Goals:
- \${whyPattern:decouple object creation from usage}
- \${benefits:easier testing and extensibility}

Provide:
1. Explanation of the pattern
2. How it applies here
3. Refactored code
4. Trade-offs to consider`} />

## 测试

### 单元测试生成

<TryIt compact prompt={`Write unit tests for this function:

Function:
\${code:paste your function here}

Testing framework: \${testFramework:pytest}

Cover:
- Happy path (normal inputs)
- Edge cases (empty, null, boundary values)
- Error cases (invalid inputs)
- \${specificScenarios:concurrent access, large inputs}

Format: Arrange-Act-Assert pattern
Include: Descriptive test names`} />

### 测试用例生成

<TryIt compact prompt={`Generate test cases for this feature:

Feature: \${featureDescription:user registration with email verification}
Acceptance criteria: \${acceptanceCriteria:user can sign up, receives email, can verify account}

Provide test cases in this format:

| ID | Scenario | Given | When | Then | Priority |
|----|----------|-------|------|------|----------|
| TC01 | ... | ... | ... | ... | High |`} />

## 架构与设计

### 系统设计

<TryIt compact prompt={`Design a system for \${requirement:real-time chat application}.

Constraints:
- Expected load: \${expectedLoad:10,000 concurrent users}
- Latency requirements: \${latency:< 100ms message delivery}
- Availability: \${availability:99.9%}
- Budget: \${budget:moderate, prefer open source}

Provide:
1. High-level architecture diagram (ASCII/text)
2. Component descriptions
3. Data flow
4. Technology choices with rationale
5. Scaling strategy
6. Trade-offs and alternatives considered`} />

### 数据库模式设计

<TryIt compact prompt={`Design a database schema for \${application:e-commerce platform}.

Requirements:
- \${feature1:User accounts with profiles and addresses}
- \${feature2:Product catalog with categories and variants}
- \${feature3:Orders with line items and payment tracking}

Provide:
1. Entity-relationship description
2. Table definitions with columns and types
3. Indexes for common queries
4. Foreign key relationships
5. Sample queries for key operations`} />

## 文档生成

### API 文档

<TryIt compact prompt={`Generate API documentation from this code:

Code:
\${code:paste your endpoint code here}

Format: \${format:OpenAPI/Swagger YAML}

Include:
- Endpoint description
- Request/response schemas
- Example requests/responses
- Error codes
- Authentication requirements`} />

### 内联文档

<TryIt compact prompt={`Add comprehensive documentation to this code:

Code:
\${code:paste your code here}

Add:
- File/module docstring (purpose, usage)
- Function/method docstrings (params, returns, raises, examples)
- Inline comments for complex logic only
- Type hints if missing

Style: \${docStyle:Google}`} />

## 来自 prompts.chat 的提示词模板

### 扮演高级开发者

```
我希望你扮演一位高级软件开发者。我会提供代码并就其提问。
你将审查代码、提出改进建议、解释概念并帮助调试问题。
你的回复应具有教育意义，帮助我成为更好的开发者。
```

### 扮演代码审查员

```
我希望你扮演一位代码审查员。我会提供包含代码变更的
Pull Request，你将对其进行全面审查。检查 bug、安全问题、
性能问题以及是否遵循最佳实践。提供建设性的反馈，
帮助开发者改进。
```

### 扮演软件架构师

```
我希望你扮演一位软件架构师。我会描述系统需求和约束条件，
你将设计可扩展、可维护的架构。解释你的设计决策、
权衡考量，并在有帮助时提供图表。
```

## 开发工作流程集成

### 提交信息生成

<TryIt compact prompt={`Generate a commit message for these changes:

Diff:
\${diff:paste git diff here}

Format: Conventional Commits
Type: \${commitType:feat}

Provide:
- Subject line (50 chars max, imperative mood)
- Body (what and why, wrapped at 72 chars)
- Footer (references issues if applicable)`} />

### PR 描述生成

<TryIt compact prompt={`Generate a pull request description:

Changes:
\${changes:list your changes or paste diff summary}

Template:
## Summary
Brief description of changes

## Changes Made
- Change 1
- Change 2

## Testing
- [ ] Unit tests added/updated
- [ ] Manual testing completed

## Screenshots (if UI changes)
placeholder

## Related Issues
Closes #\${issueNumber:123}`} />

## 总结

<Callout type="tip" title="关键技巧">
包含完整的上下文（语言、框架、约束条件），精确说明需求，请求特定的输出格式，在请求代码的同时要求解释，并包含需要处理的边界情况。
</Callout>

<Quiz 
  question="请求 AI 调试代码时，最重要的元素是什么？"
  options={[
    "仅提供编程语言",
    "预期行为、实际行为和错误信息",
    "仅提供代码片段",
    "文件名"
  ]}
  correctIndex={1}
  explanation="调试需要上下文：应该发生什么与实际发生了什么。错误信息和堆栈跟踪能帮助 AI 快速定位确切问题。"
/>

AI 是强大的编程伙伴——将其用于代码生成、审查、调试和文档编写，同时保持你自己的架构判断力。
