Prompt Writing for Programmers Cheatsheet

A User-friendly guide to writing effective prompts for AI assistance in programming. Learn how to structure your questions and requests to get the most helpful responses.

Basic Prompt Structure

Core Components

Essential elements of an effective programming prompt.

// Basic prompt structure
I need help with [specific programming task].
Language: [programming language]
Framework: [if applicable]
Current code:
```[language]
[your code here]
```
Expected behavior: [what should happen]
Current issue: [what's not working]

// Example
I need help with user authentication.
Language: JavaScript
Framework: React
Current code:
```jsx
function Login() {
  const [user, setUser] = useState(null);
  // ... rest of code
}
```
Expected: User should be authenticated and redirected
Current issue: Login state not persisting

Context Setting

Providing necessary background information.

// Project context template
Project type: [web/mobile/desktop/etc.]
Tech stack: [list main technologies]
Environment: [development/production]
Constraints: [any limitations/requirements]

// Example
Project type: Web application
Tech stack: MERN (MongoDB, Express, React, Node.js)
Environment: Development
Constraints: Must be accessible (WCAG compliant)

Code Review Prompts

Code Review Requests

How to ask for code review and improvements.

// Code review template
Please review this [language] code for:
1. Performance issues
2. Security vulnerabilities
3. Best practices
4. Potential bugs

Code:
```[language]
[code to review]
```

// Example
Please review this Python code for:
1. Performance issues
2. Security vulnerabilities
3. Best practices
4. Potential bugs

Code:
```python
def process_user_data(user_input):
    data = json.loads(user_input)
    result = db.execute(f"SELECT * FROM users WHERE id = {data['id']}")
    return result
```

Optimization Requests

How to ask for code optimization suggestions.

// Optimization template
Current performance metrics:
- Time complexity: [O notation]
- Space complexity: [O notation]
- Current runtime: [measurements]

Goals:
- Target performance: [specific metrics]
- Constraints: [limitations]

Code to optimize:
```[language]
[code here]
```

// Example
Current performance metrics:
- Time complexity: O(n²)
- Space complexity: O(n)
- Current runtime: 2.5s for 1000 items

Goals:
- Target performance: < 1s for 1000 items
- Constraints: Max memory usage 100MB

Debugging Prompts

Error Analysis

How to ask for help with debugging.

// Debugging template
Error message: [exact error message]
Stack trace: [relevant parts]
Steps to reproduce:
1. [step 1]
2. [step 2]
Expected vs Actual:
- Expected: [what should happen]
- Actual: [what's happening]
Environment details:
- OS: [operating system]
- Version: [language/framework version]

// Example
Error message: TypeError: Cannot read property 'map' of undefined
Stack trace: at UserList.render (UserList.js:15)
Steps to reproduce:
1. Load UserList component
2. Pass empty props
Expected vs Actual:
- Expected: Empty list rendered
- Actual: App crashes
Environment:
- OS: macOS 12.3
- React: 18.2.0

Bug Report

Structured way to report bugs for help.

// Bug report template
Description: [Brief description]
Severity: [Critical/High/Medium/Low]
Impact: [What functionality is affected]
Environment:
- [relevant environment details]
Reproduction:
1. [detailed steps]
Code snippet:
```[language]
[relevant code]
```
Logs/Output:
[relevant logs or console output]

// Example
Description: Authentication token expires prematurely
Severity: High
Impact: Users being logged out randomly
Environment:
- Production server
- Node.js 16.x
Reproduction:
1. Log in successfully
2. Wait 5 minutes
3. Attempt API request
Code snippet:
```javascript
const token = await auth.generateToken(user);
// Token should be valid for 24h
```
Logs:
TokenExpiredError: jwt expired

Architecture & Design

System Design Questions

How to ask about architecture and system design.

// System design template
Project scope:
- Users: [expected number]
- Data size: [expected volume]
- Traffic: [requests/second]
Requirements:
- Functional: [key features]
- Non-functional: [performance/scaling/etc.]
Current architecture:
[diagram or description]
Specific questions:
1. [question 1]
2. [question 2]

// Example
Project scope:
- Users: 1M monthly active
- Data size: 500GB
- Traffic: 1000 req/s peak
Requirements:
- Functional: Real-time chat
- Non-functional: < 100ms latency
Current architecture:
- WebSocket server
- Redis pub/sub
- PostgreSQL
Questions:
1. How to handle scaling?
2. Best caching strategy?

Code Structure

Asking for help with code organization.

// Code structure template
Project type: [type of application]
Current structure:
```
[directory tree or structure]
```
Pain points:
1. [issue 1]
2. [issue 2]
Goals:
- [goal 1]
- [goal 2]

// Example
Project type: React Native app
Current structure:
```
src/
  components/
  screens/
  utils/
  api/
```
Pain points:
1. Component reuse difficult
2. State management complex
Goals:
- Better code sharing
- Simplified state flow

Testing & QA

Test Case Design

How to ask for help with testing strategies.

// Test strategy template
Component/Feature: [name]
Test requirements:
- Unit tests: [specific needs]
- Integration tests: [specific needs]
- E2E tests: [specific needs]
Edge cases:
1. [case 1]
2. [case 2]
Current tests:
```[language]
[existing test code]
```

// Example
Component/Feature: UserAuth
Test requirements:
- Unit: Auth hooks and utils
- Integration: API calls
- E2E: Login flow
Edge cases:
1. Token expiration
2. Network failure
Current tests:
```javascript
describe('login', () => {
  it('should authenticate user', () => {
    // test code
  })
})
```

Performance Testing

Asking for help with performance testing.

// Performance test template
Scenario: [test scenario]
Metrics to measure:
- [metric 1]
- [metric 2]
Current results:
- [current measurements]
Target goals:
- [performance targets]
Test code:
```[language]
[test implementation]
```

// Example
Scenario: API endpoint load test
Metrics to measure:
- Response time
- Throughput
Current results:
- Avg response: 500ms
- Throughput: 100 req/s
Target goals:
- Avg response: < 200ms
- Throughput: 500 req/s

AI Pair Programming

Feature Implementation

How to ask AI for help implementing new features.

// Feature request template
Feature description:
[Brief description of the feature]

Technical requirements:
1. [requirement 1]
2. [requirement 2]

Current codebase context:
```[language]
[relevant existing code]
```

Integration points:
- [integration point 1]
- [integration point 2]

// Example
Feature description:
Implement user password reset functionality

Technical requirements:
1. Send reset email with token
2. Token expires in 1 hour
3. Validate new password strength

Current codebase context:
```typescript
interface AuthService {
  login(email: string, password: string): Promise<User>;
  register(user: UserDTO): Promise<User>;
  // Need to add password reset
}
```

Integration points:
- Email service
- User repository
- Authentication middleware

Code Generation

How to get AI to generate code snippets effectively.

// Code generation template
Generate [language] code for:
[specific functionality]

Requirements:
- Input: [expected input]
- Output: [expected output]
- Error handling: [requirements]
- Style guide: [coding standards]

// Example
Generate TypeScript code for:
API response caching decorator

Requirements:
- Input: Cache key and duration
- Output: Cached API response
- Error handling: Return fresh data if cache fails
- Style guide: Follow Angular style guide

Additional context:
- Use Redis for storage
- Handle concurrent requests
- Type-safe implementation

Refactoring Assistance

Code Improvement

How to ask for code refactoring suggestions.

// Refactoring template
Current code issues:
1. [issue 1]
2. [issue 2]

Refactoring goals:
- [goal 1]
- [goal 2]

Code to refactor:
```[language]
[code needing improvement]
```

Constraints:
- [constraint 1]
- [constraint 2]

// Example
Current code issues:
1. Too many responsibilities
2. Duplicate logic
3. Poor error handling

Refactoring goals:
- Single responsibility
- DRY implementation
- Robust error handling

Code to refactor:
```typescript
class UserService {
  async createUser(data) {
    // 100 lines of mixed concerns
  }
}
```

Constraints:
- Must maintain API compatibility
- Zero downtime deployment

Pattern Implementation

Request help implementing design patterns.

// Design pattern template
Pattern: [pattern name]
Use case: [specific situation]

Current implementation:
```[language]
[current code]
```

Desired outcome:
[what you want to achieve]

// Example
Pattern: Observer
Use case: Notification system

Current implementation:
```typescript
class NotificationService {
  // Direct coupling to email and push
}
```

Desired outcome:
Decoupled notification channels with easy addition of new channels

Security Reviews

Security Audit

How to request security reviews of your code.

// Security review template
Code context:
[Brief description of the code's purpose]

Security requirements:
1. [requirement 1]
2. [requirement 2]

Code for review:
```[language]
[code to review]
```

Specific concerns:
- [concern 1]
- [concern 2]

// Example
Code context:
User authentication middleware

Security requirements:
1. OWASP Top 10 compliance
2. GDPR compliance
3. Rate limiting

Code for review:
```javascript
const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization;
  // ... authentication logic
}
```

Specific concerns:
- Token validation
- Session management
- XSS prevention

Vulnerability Assessment

How to ask for vulnerability assessments.

// Vulnerability check template
Application type: [web/mobile/desktop]
Tech stack: [technologies used]
Critical assets:
- [asset 1]
- [asset 2]

Code sample:
```[language]
[potentially vulnerable code]
```

Focus areas:
1. [area 1]
2. [area 2]

// Example
Application type: Web API
Tech stack: Node.js, Express, MongoDB
Critical assets:
- User credentials
- Payment information
- Personal data

Code sample:
```javascript
app.post('/api/payment', async (req, res) => {
  const { cardNumber, cvv } = req.body;
  // Payment processing logic
});
```

Focus areas:
1. Data encryption
2. Input validation
3. Access control

Performance Optimization

Performance Analysis

How to request performance optimization help.

// Performance analysis template
Performance metrics:
- Current: [current metrics]
- Target: [target metrics]

Bottleneck suspicion:
[Where you think the issue is]

Profiling data:
```
[profiling results]
```

Code section:
```[language]
[code to optimize]
```

// Example
Performance metrics:
- Current: 2s page load
- Target: < 500ms page load

Bottleneck suspicion:
React component re-rendering

Profiling data:
```
React DevTools Profiler output
[...]
```

Code section:
```jsx
function DataGrid({ data }) {
  // Component code
}
```

Resource Optimization

How to ask for resource usage optimization.

// Resource optimization template
Resource type:
- [CPU/Memory/Network/etc.]

Current usage:
- [current metrics]

Target usage:
- [target metrics]

Code:
```[language]
[resource-intensive code]
```

// Example
Resource type:
- Memory usage

Current usage:
- 1.5GB heap

Target usage:
- < 500MB heap

Code:
```javascript
function processLargeDataset(data) {
  // Memory-intensive operations
}
```