Prompt Engineering for Developers — 30 Ready-to-Use Templates
Chapter 8: Prompt Engineering for Developers — 30 Ready-to-Use Templates
Prompt engineering is not mystical — it follows clear patterns. The difference between a good and bad prompt is not eloquence; it's whether the information is complete, constraints are explicit, and expectations are specific. This chapter provides 30 ready-to-use templates for developers' most common scenarios, in 6 categories of 5 each.
Why Most Prompts Underperform
Common flaws in bad prompts:
- Describes what you want without stating constraints
- No error messages, no current code
- No context (which framework, which version, which project)
Comparison:
Bad prompt:
Write a login feature
Good prompt:
@src/routes/auth.ts @src/services/UserService.ts
Add a login endpoint to the existing Express + TypeScript project:
POST /api/auth/login
Request body: { email: string, password: string }
Validation: use zod for format; bcrypt for password; return JWT on success (7-day expiry)
Failure: always return { error: "Invalid credentials" } — don't distinguish between "user not found" and "wrong password"
Constraint: do not modify UserService's interface; only add route handling in auth.ts
The gap: the good prompt includes file paths, specific interface specs, error handling requirements, and constraints. With this information, AI can generate code that's directly usable.
30 Ready-to-Use Templates
Category 1: Understanding Code (1-5)
Template 1: Understand an unfamiliar function
@file_path
Explain the [function_name] function:
1. What it does (one sentence)
2. What each parameter means and its valid range
3. The structure of the return value
4. Key processing steps (3-5 steps)
5. Possible edge cases and exceptions
Template 2: Understand complex business logic
@file1 @file2
I need to understand the complete processing flow of [feature name].
Starting from [entry point], trace the data flow:
- What transformation happens at each step
- Where the conditional branches are
- What format the final result is in
Use numbered steps, natural language — not code.
Template 3: Compare two implementations
@fileA @fileB
Both files implement [same feature]. Compare and analyze:
1. Core implementation approach differences
2. Performance differences (if any)
3. Pros and cons of each
4. Which one you recommend keeping, and why
Template 4: Identify potential problems
@file_path
Read this code carefully and find:
1. Possible bugs (especially edge cases, null values, concurrency)
2. Security vulnerabilities (if any)
3. Performance bottlenecks (if any)
4. Readability problems
For each issue: location (line number), risk level (high/medium/low), reason.
Only report real problems — no generic observations.
Template 5: Reconstruct design intent
@file_path
This code has no comments. Help me infer the design intent:
1. What problem does this class/module solve?
2. Why is it designed this way rather than something simpler?
3. Which design decisions are worth preserving?
4. Which parts might be historical technical debt?
Infer from the code itself — don't speculate.
Category 2: Fixing Bugs (6-10)
Template 6: Precise bug location
@relevant_file
Bug found:
- Trigger: [specific steps to reproduce]
- Expected behavior: [what should happen]
- Actual behavior: [what actually happens]
- Error message: [full stack trace, if any]
- Environment: [Node 18 / Python 3.11 / browser version etc.]
Please:
1. Identify the root cause (not just the symptom)
2. Provide the fix
3. Explain why this fix works
4. Recommend whether to add a regression test
Template 7: Fix a type error
@file_path
TypeScript error:
[full error message]
I want to maintain type safety — no `any` to bypass.
Analyze the cause of the error, provide the correct type fix, and explain why your approach is correct.
Template 8: Fix async issues
@file_path
This async code has a problem — symptom: [describe symptom].
Suspected cause: [race condition / Promise chain error / wrong await placement].
Please:
1. Analyze the async execution order
2. Identify the problem
3. Provide the complete fixed code
Template 9: Fix a performance problem
@file_path
Performance issue:
- Operation: [what operation]
- Data size: [number of records]
- Current time: [seconds/ms]
- Target: [seconds/ms]
Analyze possible bottlenecks and provide an optimization plan.
If it's a database query problem, provide the optimized query and recommended indexes.
Template 10: Third-party library problem
@Web
Issue with [library name] [version]:
- Operation: [specific operation]
- Error: [error message]
- My code: [relevant snippet]
Search for the latest solution (this library version is recent; there may be breaking changes).
Provide: root cause, correct usage example, whether a version upgrade is needed.
Category 3: Building Features (11-15)
Template 11: Complete feature implementation
@stack_related_files @existing_similar_feature
Implement [feature name] in [project/module]:
Requirements:
- [specific requirement 1]
- [specific requirement 2]
Technical requirements:
- Use [specified tech/library]
- Follow the code style in @existing_feature_file
- Error handling: [specific requirements]
Constraints:
- Do not modify [which files/interfaces]
- Do not introduce new dependencies (or only allow [specific dep])
Template 12: API endpoint
Implement API endpoint: [HTTP method] [path]
Request:
- Auth: [required/not required] JWT
- Body: [fields and types]
- Validation rules: [requirements]
Response:
- Success [status code]: [response format]
- Error cases: [handling for each error]
Database operations: [what CRUD operations needed]
Follow the style of existing endpoint implementations.
Template 13: Database model design
Design a database model to satisfy these business requirements:
[business requirement description]
Requirements:
- Primary key type: UUID / auto-increment integer
- Timestamp fields: createdAt, updatedAt
- Soft delete: [yes/no] deletedAt
- Relationships: [describe entity relationships]
Provide:
1. Model definition (in [Prisma/SQLAlchemy/Go struct])
2. Recommended indexes (explain why)
3. Constraints to be aware of
Template 14: Frontend component
Implement React component: [ComponentName]
Function: [what the component does]
Props interface:
- [propName]: [type] — [description]
Interaction logic:
- [user action 1] → [what happens]
- [user action 2] → [what happens]
Style: use Tailwind, follow the style in @existing_component.
No Storybook needed, just the main file.
Template 15: Utility function
Implement utility function [function_name]:
Function: [one sentence]
Input: [parameters and types]
Output: [return type and format]
Edge case handling:
- Empty/null input: [expected behavior]
- Out-of-range input: [expected behavior]
- Concurrent calls (if applicable): [expected behavior]
Requirements: pure function, no side effects, JSDoc comment, with unit tests.
Category 4: Refactoring (16-20)
Template 16: Extract shared logic
@fileA @fileB @fileC
These files all have similar [feature description] with duplicate code.
Please:
1. Find the extractable common logic
2. Design a suitable interface (params, return values)
3. Implement the extracted shared function/module
4. Modify existing callers, showing the changed code
5. State whether tests need updating
Template 17: Refactor a large function
@file_path
This function exceeds [N] lines and has poor readability. Refactor it while preserving exact same behavior:
1. Identify sub-logic blocks that can be extracted
2. Name each sub-logic (names should be self-explanatory)
3. Provide the complete refactored code
4. The external interface must be completely unchanged
Change the structure only — no behavior changes.
Template 18: Improve error handling
@file_path
Error handling in this module is inadequate. Improvements needed:
1. All places that can throw exceptions must have try/catch
2. Errors must be logged appropriately (use structlog/winston)
3. User-facing error messages must not expose internal details
4. Each error type must have the appropriate HTTP status code (for API endpoints)
Provide the complete refactored code.
Template 19: Add TypeScript types
@file_path
This JS file needs to be migrated to TypeScript. Requirements:
1. Add types to all function parameters and return values
2. Add interface definitions for all objects
3. No `any` (unless there's truly no alternative; add a comment explaining)
4. Use `unknown` + type guards instead of `as` assertions
Provide the complete TypeScript version.
Template 20: Performance optimization
@file_path
Analyze and optimize performance:
Current state: [operation, data size, execution time]
Target: [desired execution time]
Check for:
- N+1 queries
- Missing necessary caching
- Unnecessary loops or repeated computation
- Serial operations that could be parallelized
Provide the optimization plan and expected improvement.
Category 5: Testing (21-25)
Template 21: Unit tests
@file_path
Write unit tests for [function/class]:
Framework: [Jest/pytest/Go test]
Must cover:
1. Happy path
2. Edge cases: [empty input, max value, min value, etc.]
3. Error cases: [each possible error]
Tests must be genuinely useful — not just "function was called." Validate actual output and side effects.
Template 22: Integration tests
@route_file @service_file
Write integration tests for [API path]:
- Mock external dependencies (database/third-party APIs)
- Cover success scenario and all failure scenarios
- Verify response format, status codes, and database state changes
Implement with [Supertest/pytest/httptest].
Template 23: Fill coverage gaps
@file_path @test_file
Current test coverage is insufficient. Analyze untested code paths:
1. Which branches have no test coverage
2. Which edge cases are missing
3. Which error paths are untested
Provide additional test cases, matching the style of the existing test file.
Template 24: Mock complex dependencies
@file_path
This code depends on [external service/database]. Mocking needed for tests.
Implement:
1. Mock [dependency name]'s methods: [list of methods]
2. Simulate successful return data structures
3. Simulate various failures (timeout, permission denied, network error)
4. Show how to use these mocks in tests
Template 25: Refactor tests
@test_file
This test file has problems: [describe problems: lots of duplication, tests interdependent, setup too complex].
Refactoring goals:
1. Extract common setup/teardown logic
2. Each test must be independent — no side-effect dependencies
3. Test names must describe intent
Keep the same test coverage; change structure only.
Category 6: Documentation and Tooling (26-30)
Template 26: Generate API docs
@route_file
Generate OpenAPI/Swagger documentation for this API module:
- Path, method, description for each endpoint
- Request parameter and body schemas
- Response format (success and error)
- Authentication requirements
Output in YAML format.
Template 27: Code comments
@file_path
Add comments to this code:
- Complex logic: the why (why this way, not what it does)
- Public functions: JSDoc/docstring
- Non-obvious data structures: explanation
- Known edge cases and known technical debt
Comments must add real value — not "this function returns a list of users."
Template 28: Generate CHANGELOG
@Git
Based on recent git commits, generate a CHANGELOG for v[version]:
- Format: ## [Version] - [Date] / ### Added / ### Changed / ### Fixed
- User-facing perspective, not developer-facing (no internal refactors)
- Merge related small commits into one entry
- Sort by importance
Template 29: Generate README
@src/ @package.json @README.md (if exists)
Generate a complete README for this project:
- Project description (one sentence)
- Feature list (user perspective)
- Quick start (minimum steps to run in 5 minutes)
- Environment variable reference (extracted from .env.example or code)
- Development guide (how to run tests, how to contribute)
Markdown format. Keep it concise — no fluff.
Template 30: Generate Makefile/scripts
Generate a Makefile for this project with common commands:
- make dev: start development environment
- make test: run tests
- make lint: code linting
- make build: production build
- make clean: clean build artifacts
- make help: show all command descriptions
Reference @package.json scripts and convert to Make targets.
Multi-Turn Conversation Rhythm
Good prompt engineering isn't just a single question — it's a multi-turn rhythm:
- Round 1: Understand and confirm — describe the need, let AI restate its understanding and confirm direction
- Round 2: Generate a draft — generate code based on the confirmed direction
- Round 3: Iterate on details — make fine-grained adjustments on specific issues
- Round 4: Validate and test — let AI help identify edge cases and generate tests
Keep each round focused. Don't try to solve everything in one prompt.
Chapter Key Points
- Prompt quality is about information completeness, not wording: File paths, specific errors, constraints — all required.
- 30 templates covering 6 major scenarios: Understanding code, fixing bugs, building features, refactoring, testing, documentation — copy and adapt directly.
- Multi-turn dialogue beats single-turn: Understand → Draft → Iterate → Validate. One concern per round.
- Constraints and expected outcomes matter equally: "Don't change the function signature," "don't add new dependencies" — state them explicitly.
- Give AI enough context to make decisions: Without the tech stack, framework version, and project background, AI can only use generic assumptions.