practical applications ยท 9 menit baca
Coding Assistant Prompts
Prompt patterns untuk GitHub Copilot, Cursor, ChatGPT, dan AI coding tools
Introduction
AI coding assistants seperti GitHub Copilot, Cursor, ChatGPT, dan Claude dapat mempercepat development jika Anda tahu cara berkomunikasi dengan mereka. Prompt yang baik menghasilkan code yang production-ready, bukan code yang butuh heavy refactoring.
Lesson ini membahas prompt patterns untuk common coding tasks: writing functions, debugging, refactoring, code review, dan documentation.
Prinsip Dasar Coding Prompts
1. Specify Tech Stack
AI perlu tahu environment Anda untuk generate code yang compatible.
Before
8 tokensBuatkan authentication functionAfter
32 tokensBuatkan authentication function untuk Next.js 14 App Router. Tech: TypeScript, NextAuth.js v5, Prisma, PostgreSQL. Return type: Promise<User | null>.2. Provide Context
Beri context tentang existing codebase agar code baru fit seamlessly.
Context yang relevan:
- Naming conventions (camelCase, snake_case, PascalCase)
- File structure (where this code will live)
- Existing patterns (how similar features are implemented)
- Dependencies (what's already imported/available)
Before
15 tokensBuatkan function untuk fetch user data dari APIAfter
52 tokensBuatkan function fetchUserData() di src/lib/api.ts. Existing pattern: semua API calls pakai custom fetcher di lib/fetcher.ts yang handle auth headers. Return type: Promise<User>. Error handling: throw ApiError dengan message dan status code.3. Specify Constraints
Beri batasan untuk menghindari over-engineering atau anti-patterns.
| Technique | When to Use | Token Cost | Quality | Complexity |
|---|---|---|---|---|
| No External Deps | Minimize bundle size | Low | High | Medium |
| Pure Functions | Testability penting | Low | High | Low |
| Type Safety | TypeScript strict mode | Medium | High | Medium |
| Performance | High-traffic endpoints | Medium | High | High |
Prompt Patterns untuk Common Tasks
Pattern 1: Writing New Functions
Template:
Write a [function name] that [what it does].
Tech: [language, framework, libraries]
Input: [parameter types and descriptions]
Output: [return type and format]
Constraints: [performance, dependencies, patterns]
Error handling: [how to handle errors]
Example usage:
[show how function will be called]
Contoh konkret:
Write a validateEmail function that checks if email format is valid.
Tech: TypeScript, no external libraries
Input: email (string)
Output: boolean (true if valid, false if invalid)
Constraints:
- Pure function (no side effects)
- Support international domains
- Reject disposable email providers
Error handling: return false for invalid input, don't throw
Example usage:
validateEmail("user@example.com") // true
validateEmail("invalid") // false
Pattern 2: Debugging Code
Template:
This code has a bug: [describe symptom]
[paste code]
Expected behavior: [what should happen]
Actual behavior: [what's happening]
Error message (if any): [paste error]
Find the bug and explain the fix.
Contoh konkret:
This code has a bug: user data tidak tersimpan ke database
async function saveUser(data) {
const user = await prisma.user.create({ data });
return user;
}
Expected: user data tersimpan dan return user object
Actual: function return user object tapi data tidak ada di database
Error: tidak ada error message
Find the bug and explain the fix.
Pattern 3: Refactoring
Template:
Refactor this code to [improvement goal].
[paste code]
Requirements:
- [maintain backward compatibility / breaking changes OK]
- [preserve existing tests / update tests]
- [specific patterns to follow]
Constraints:
- [no new dependencies]
- [maintain performance]
Contoh konkret:
Refactor this code to improve readability and type safety.
function processData(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
if (data[i].status === 'active') {
result.push({
id: data[i].id,
name: data[i].name,
value: data[i].value * 2
});
}
}
return result;
}
Requirements:
- Convert to TypeScript with proper types
- Use modern array methods (filter, map)
- Maintain backward compatibility (same input/output)
Constraints:
- No external libraries
- Keep function pure (no side effects)
Pattern 4: Code Review
Template:
Review this code for [focus areas].
[paste code]
Check for:
- [security issues]
- [performance problems]
- [code smells]
- [best practices violations]
Provide: issue description, severity (high/medium/low), suggested fix.
Contoh konkret:
Review this API endpoint for security and performance issues.
app.post('/api/users', async (req, res) => {
const { email, password } = req.body;
const user = await db.query(`SELECT * FROM users WHERE email = '${email}'`);
if (user) {
return res.status(400).json({ error: 'User exists' });
}
const newUser = await db.query(`INSERT INTO users (email, password) VALUES ('${email}', '${password}')`);
res.json(newUser);
});
Check for:
- SQL injection vulnerabilities
- Password security issues
- Error handling gaps
- Performance bottlenecks
Format: [SEVERITY] Issue: ... | Fix: ...
Pattern 5: Writing Tests
Template:
Write tests for this function using [test framework].
[paste function]
Test cases to cover:
- [happy path]
- [edge cases]
- [error cases]
Test style: [unit / integration]
Mocking: [what to mock, what to test real]
Contoh konkret:
Write tests for this function using Jest and React Testing Library.
function calculateDiscount(price, discountPercent) {
if (price < 0 || discountPercent < 0 || discountPercent > 100) {
throw new Error('Invalid input');
}
return price * (1 - discountPercent / 100);
}
Test cases to cover:
- Normal discount (price=100, discount=20 โ 80)
- Zero discount (price=100, discount=0 โ 100)
- Full discount (price=100, discount=100 โ 0)
- Invalid price (negative โ throw error)
- Invalid discount (>100 โ throw error)
Test style: unit tests
Mocking: none (pure function)
Pattern 6: Documentation
Template:
Write documentation for this [function/class/module].
[paste code]
Include:
- Purpose and use case
- Parameters with types and descriptions
- Return value with type
- Example usage
- Edge cases and gotchas
Format: [JSDoc / TSDoc / docstring / markdown]
Contoh konkret:
Write JSDoc documentation for this function.
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
lastError = error;
if (i < maxRetries - 1) await sleep(1000 * (i + 1));
}
}
throw lastError;
}
Include:
- Purpose: retry failed HTTP requests with exponential backoff
- Parameters: url, options, maxRetries
- Return: parsed JSON response
- Throws: error after all retries exhausted
- Example usage
Format: JSDoc with @param, @returns, @throws
Advanced Patterns
Multi-Step Code Generation
Untuk complex features, break down menjadi steps.
Pattern:
I need to implement [feature]. Break it down into steps.
Requirements: [list requirements]
Tech stack: [list tech]
For each step, provide:
1. What to build
2. Files to create/modify
3. Code snippets
4. Testing approach
Contoh:
I need to implement user authentication with email/password.
Requirements:
- Sign up with email verification
- Login with JWT tokens
- Password reset flow
- Protected routes
Tech: Next.js 14, Prisma, PostgreSQL, NextAuth.js
Break down into steps with code for each step.
Pair Programming Pattern
Iterative refinement dengan AI sebagai pair programmer.
Flow:
Step 1: "Write initial implementation of [feature]"
โ AI generates code
Step 2: "This code has issue: [describe]. Fix it."
โ AI fixes
Step 3: "Add error handling for [edge case]"
โ AI adds error handling
Step 4: "Optimize for performance: [specific concern]"
โ AI optimizes
Step 5: "Write tests for this implementation"
โ AI writes tests
Tool-Specific Tips
GitHub Copilot
- Write descriptive function names โ Copilot autocompletes implementation
- Add comments above function โ Copilot generates based on comment
- Start typing test cases โ Copilot suggests more test cases
Example:
// Function to validate credit card number using Luhn algorithm
// Returns true if valid, false otherwise
function validateCreditCard(cardNumber: string): boolean {
// Copilot will autocomplete the implementation
ChatGPT / Claude
- Use multi-turn conversations untuk complex features
- Ask for explanations: "Explain why you chose this approach"
- Request alternatives: "Show 2 other ways to implement this"
Cursor
- Use
@codebaseuntuk reference existing code patterns - Use
@docsuntuk reference official documentation - Use
@webuntuk search current best practices
Common Pitfalls
Checklist sebelum commit AI-generated code:
- Code follows project conventions
- No security vulnerabilities (SQL injection, XSS, etc.)
- Error handling comprehensive
- Edge cases covered
- Tests written and passing
- Performance acceptable
- No unnecessary dependencies added
Summary
Prompt patterns untuk coding tasks:
- Writing functions โ specify tech, input/output, constraints, example usage
- Debugging โ describe symptom, expected vs actual behavior, paste error
- Refactoring โ state goal, requirements, constraints
- Code review โ specify focus areas, request severity + fix
- Writing tests โ list test cases, specify framework, mocking strategy
- Documentation โ request format (JSDoc/TSDoc), include examples
Best practices:
- Always specify tech stack dan versions
- Provide context tentang existing codebase
- Give constraints untuk avoid over-engineering
- Use iterative refinement untuk complex features
- Always review dan test AI-generated code
AI coding assistants mempercepat development, tapi Anda tetap responsible untuk code quality dan security.