Prompt Engineering for Programmers: Getting AI to Generate Better Code
Master prompt writing techniques to get Claude, GPT, and other AI tools to generate more accurate and higher quality code.
Why Prompts Matter
The same AI tool with different prompts produces vastly different results. A good prompt can transform AI-generated code from "barely functional" to "production-ready."
Golden Rules for Prompt Writing
1. Specific > Vague
❌ Bad Prompt:
Write a validation function
✅ Good Prompt:
Write a TypeScript function validateEmail with requirements:
- Parameter: email: string
- Return: { valid: boolean; error?: string }
- Validation rules:
1. Must contain @ symbol
2. Must have characters before and after @
3. Domain part must contain .
- Use regex implementation
- Add JSDoc comments
2. Provide Context
Tell AI about your tech stack and constraints:
In my Next.js 14 project (using App Router),
create a user login API route with requirements:
- Use zod for request body validation
- Use bcrypt for password comparison
- Return JWT token
- Handle all possible error scenarios
3. Give Examples
Based on the following code style, create a function to get order details:
// Example: Get user info
export async function getUserById(id: string) {
const user = await prisma.user.findUnique({
where: { id },
select: {
id: true,
name: true,
email: true,
}
});
if (!user) {
throw new NotFoundError('User not found');
}
return user;
}
// Please create: Get order details, including order items and user information
4. Break Down Complex Tasks
Split complex tasks into steps:
Step 1: First help me design the database schema,
I need a blogging system with articles, categories, tags, comments
Step 2: (After getting schema)
Based on this schema, create Prisma models
Step 3: (After getting models)
Create CRUD API for articles module
Practical Prompt Templates
Template 1: Code Refactoring
Refactor the following code with requirements:
1. Follow SOLID principles
2. Extract repeated logic
3. Add appropriate error handling
4. Maintain original functionality
5. Add type annotations
Original code:
[Paste code]
Template 2: Bug Fixing
This code has a bug that manifests as [describe symptoms].
Expected behavior: [describe expected]
Actual behavior: [describe actual]
Please:
1. Analyze possible causes
2. Provide fix solution
3. Explain why this fixes it
Code:
[Paste code]
Template 3: Code Review
Please review the following code from these perspectives:
- Security vulnerabilities
- Performance issues
- Code readability
- Potential bugs
- Best practices
Code:
[Paste code]
Template 4: Learning New Technology
I'm a React developer with 3 years of experience,
and now need to learn [new technology name].
Please:
1. Explain core concepts using React analogies
2. Provide a simple entry-level example
3. List 3 common pitfalls
4. Recommend learning path
Advanced Techniques
Role Setting
You are a backend architect with 10 years of experience,
focused on high-concurrency system design.
Please evaluate the scalability of the following API design...
Constraints
Complete the task under these constraints:
- Don't use any third-party libraries
- Keep code to under 50 lines
- Time complexity must be O(n)
Chain of Thought
Think through this problem step by step:
1. First analyze requirements
2. Consider possible solutions
3. Evaluate pros and cons of each
4. Choose best solution and implement
Common Mistakes
- Too vague: No specific requirements
- Too wordy: Too much irrelevant information
- Missing context: Don't mention tech stack and constraints
- Asking too much at once: Not breaking down complex tasks
Summary
Good Prompt = Specific Requirements + Sufficient Context + Clear Constraints + Expected Output Format
Spend 2 minutes writing a good prompt, save 20 minutes debugging AI-generated code.
Practice Tip: Create a prompt template library, save your commonly used prompts, and just tweak them each time.