Programming & Development
Code generation and debugging
AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows.
AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing.
Code Generation
Do's and Don'ts: Code Prompts
❌ Vague request
Write a function to validate emails.
✓ Complete specification
Write a Python function that validates email addresses. Input: string (potential email) Output: tuple[bool, str | None] - (is_valid, error_message) Handle: empty string, None, unicode chars Use regex, include type hints and docstring.
Function Generation
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 handlingClass/Module Generation
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 skeletonAPI Endpoint Generation
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 considerationDebugging
Always include the expected behavior, actual behavior, and error message (if any). The more context you provide, the faster AI can identify the root cause.
Bug Analysis
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 explanationError Message Interpretation
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 futurePerformance Debugging
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 improvementCode Review
Do's and Don'ts: Code Review Prompts
❌ Generic request
Review this code.
✓ Specific criteria
Review this code for a pull request. Check for: 1. Correctness: bugs, logic errors, edge cases 2. Security: injection risks, auth issues 3. Performance: N+1 queries, memory leaks 4. Maintainability: naming, complexity Format: 🔴 Critical / 🟡 Important / 🟢 Suggestion
Comprehensive Review
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 neededSecurity Review
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 remediationRefactoring
Code Smell Detection
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.Design Pattern Application
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 considerTesting
Unit Test Generation
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 namesTest Case Generation
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 |Architecture & Design
System Design
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 consideredDatabase Schema Design
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 operationsDocumentation Generation
API Documentation
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 requirementsInline Documentation
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}Prompt Templates from prompts.chat
Act as a Senior Developer
I want you to act as a senior software developer. I will provide
code and ask questions about it. You will review the code, suggest
improvements, explain concepts, and help debug issues. Your
responses should be educational and help me become a better
developer.
Act as a Code Reviewer
I want you to act as a code reviewer. I will provide pull requests
with code changes, and you will review them thoroughly. Check for
bugs, security issues, performance problems, and adherence to best
practices. Provide constructive feedback that helps the developer
improve.
Act as a Software Architect
I want you to act as a software architect. I will describe system
requirements and constraints, and you will design scalable,
maintainable architectures. Explain your design decisions,
trade-offs, and provide diagrams where helpful.
Development Workflow Integration
Commit Message Generation
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 Description Generation
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}Summary
Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle.
What's the most important element to include when asking AI to debug code?
AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment.