Intermediate20 min

Build a library of reusable prompt templates for common development tasks—from code generation to debugging to documentation.

Prompt Templates and Patterns

Creating effective prompts from scratch every time is inefficient. Building a library of reusable templates accelerates your workflow and ensures consistent quality.

Why Use Templates?

Templates provide:

  • Consistency - Same quality across all requests
  • Speed - Fill in blanks instead of composing from scratch
  • Best practices - Encode lessons learned
  • Team alignment - Shared standards across developers

Template Structure

A good template has:

Terminal
[VARIABLES] - Placeholders you fill in
[FIXED TEXT] - Standard instructions that don't change
[OPTIONAL SECTIONS] - Include when relevant

Code Generation Templates

Function Generation

Terminal
Generate a [LANGUAGE] function with the following specifications:

Function name: [FUNCTION_NAME]
Purpose: [DESCRIPTION]

Parameters:
[PARAMETER_LIST]

Return type: [RETURN_TYPE]

Requirements:
- [REQUIREMENT_1]
- [REQUIREMENT_2]

Constraints:
- [CONSTRAINT_1]
- [CONSTRAINT_2]

Example usage:
[EXAMPLE_CODE]

Include:
- [ ] JSDoc/docstring comments
- [ ] Input validation
- [ ] Error handling
- [ ] Unit test examples

Filled Example:

Terminal
Generate a TypeScript function with the following specifications:

Function name: calculateDiscount
Purpose: Calculate the final price after applying discount codes

Parameters:
- originalPrice: number (the base price)
- discountCode: string (the discount code to apply)
- userTier: 'basic' | 'premium' | 'vip' (affects discount multiplier)

Return type: { finalPrice: number; discountApplied: number; }

Requirements:
- Validate discount code against allowed codes list
- Apply tier multiplier (basic: 1x, premium: 1.2x, vip: 1.5x)
- Round to 2 decimal places

Constraints:
- Discount cannot exceed original price
- Invalid codes should return original price with 0 discount

Include:
- [x] JSDoc comments
- [x] Input validation
- [x] Error handling
- [ ] Unit test examples

Component Generation

Terminal
Create a [FRAMEWORK] component with these specifications:

Component name: [COMPONENT_NAME]
Type: [FUNCTIONAL|CLASS]

Props:
[PROPS_WITH_TYPES]

State (if any):
[STATE_VARIABLES]

Features:
- [FEATURE_1]
- [FEATURE_2]

Styling: [STYLING_APPROACH]

Accessibility requirements:
- [A11Y_REQUIREMENT]

Follow this existing pattern:
```typescript
[EXAMPLE_COMPONENT]
Terminal

### API Endpoint Generation

Create a [FRAMEWORK] API endpoint:

Method: [HTTP_METHOD] Path: [ENDPOINT_PATH] Purpose: [DESCRIPTION]

Request:

  • Body/Query: [REQUEST_SCHEMA]
  • Headers: [REQUIRED_HEADERS]

Response:

  • Success ([STATUS_CODE]): [SUCCESS_SCHEMA]
  • Error ([ERROR_CODES]): [ERROR_SCHEMA]

Requirements:

  • Authentication: [AUTH_TYPE]
  • Validation: [VALIDATION_LIB]
  • Rate limiting: [YES/NO]

Database operations: [DESCRIBE_DB_OPS]

Error handling: [ERROR_HANDLING_PATTERN]

Terminal

## Debugging Templates

### Error Analysis

Analyze this error and help me fix it.

Error Type: [ERROR_TYPE] Error Message:

Terminal
[FULL_ERROR_MESSAGE]

Stack Trace:

Terminal
[STACK_TRACE]

Relevant Code:

Terminal
[CODE_WHERE_ERROR_OCCURS]

Context:

  • Environment: [ENVIRONMENT]
  • When it occurs: [TRIGGER_CONDITIONS]
  • Frequency: [ALWAYS|SOMETIMES|RARELY]

What I've tried:

  • [ATTEMPT_1]
  • [ATTEMPT_2]

Please:

  1. Explain what this error means
  2. Identify the root cause
  3. Suggest a fix with code
  4. Explain how to prevent this in the future
Terminal

### Performance Investigation

Investigate this performance issue.

Symptom: [DESCRIPTION_OF_SLOWNESS]

Metrics:

  • Current: [CURRENT_PERFORMANCE]
  • Expected: [EXPECTED_PERFORMANCE]
  • Measured using: [MEASUREMENT_METHOD]

Code under investigation:

Terminal
[SLOW_CODE]

Context:

  • Data size: [DATA_SIZE]
  • Frequency of execution: [CALL_FREQUENCY]
  • Environment: [ENVIRONMENT]

Questions:

  1. What is causing the performance issue?
  2. What is the current time/space complexity?
  3. How can this be optimized?
  4. What's the expected improvement?
Terminal

## Refactoring Templates

### Code Cleanup

Refactor this code for better [QUALITY_ASPECT].

Current code:

Terminal
[CODE_TO_REFACTOR]

Issues with current code:

  • [ISSUE_1]
  • [ISSUE_2]

Refactoring goals:

  • [GOAL_1]
  • [GOAL_2]

Constraints:

  • Must preserve: [BEHAVIOR_TO_KEEP]
  • Must not change: [API_CONSTRAINTS]
  • Must remain compatible with: [COMPATIBILITY_REQUIREMENTS]

Style guide: [RELEVANT_STYLE_RULES]

Terminal

### Pattern Migration

Migrate this code from [OLD_PATTERN] to [NEW_PATTERN].

Current implementation ([OLD_PATTERN]):

Terminal
[CURRENT_CODE]

Target pattern ([NEW_PATTERN]): Example of target pattern:

Terminal
[PATTERN_EXAMPLE]

Requirements:

  • Maintain identical functionality
  • Follow the new pattern consistently
  • Update any related imports/dependencies

After migration, verify:

  • [VERIFICATION_1]
  • [VERIFICATION_2]
Terminal

## Review Templates

### Code Review

Review this code for [REVIEW_FOCUS].

Code to review:

Terminal
[CODE]

Context:

  • Purpose: [CODE_PURPOSE]
  • Part of: [LARGER_FEATURE]
  • Author experience level: [JUNIOR|MID|SENIOR]

Review criteria:

  • Correctness
  • Security
  • Performance
  • Maintainability
  • Test coverage
  • Documentation

Provide feedback in this format:

  • Critical: Must fix before merge
  • Important: Should fix
  • Minor: Nice to have
  • Positive: What's done well
Terminal

### Security Audit

Perform a security review of this code.

Code:

Terminal
[CODE]

Context:

  • Handles: [DATA_TYPE] (e.g., user input, payments, PII)
  • Exposed via: [EXPOSURE_POINT] (e.g., public API, internal service)
  • Authentication: [AUTH_METHOD]

Check for:

  • Injection vulnerabilities (SQL, NoSQL, Command)
  • XSS vulnerabilities
  • Authentication/Authorization flaws
  • Sensitive data exposure
  • Security misconfiguration
  • Vulnerable dependencies

For each issue found, provide:

  1. Vulnerability type
  2. Severity (Critical/High/Medium/Low)
  3. Location in code
  4. Exploitation scenario
  5. Recommended fix
Terminal

## Documentation Templates

### Function Documentation

Write documentation for this function.

Function:

Terminal
[FUNCTION_CODE]

Documentation style: [JSDOC|DOCSTRING|MARKDOWN]

Include:

  • Purpose description
  • Parameter descriptions with types
  • Return value description
  • Exceptions/errors that can be thrown
  • Usage examples (at least 2)
  • Edge cases to be aware of
Terminal

### API Documentation

Generate API documentation for this endpoint.

Endpoint code:

Terminal
[ENDPOINT_CODE]

Documentation format: [OPENAPI|MARKDOWN|CUSTOM]

Include:

  • Endpoint description
  • Request format (method, path, headers, body)
  • Response formats (success and error cases)
  • Authentication requirements
  • Rate limits
  • Example requests and responses
  • Common error scenarios
Terminal

## Testing Templates

### Unit Test Generation

Generate unit tests for this function.

Function to test:

Terminal
[FUNCTION_CODE]

Testing framework: [JEST|PYTEST|MOCHA|etc]

Test coverage requirements:

  • Happy path scenarios
  • Edge cases
  • Error conditions
  • Boundary values

Mocking needs: [DEPENDENCIES_TO_MOCK]

Follow this test structure:

Terminal
[EXAMPLE_TEST_STRUCTURE]
Terminal

### Integration Test Generation

Generate integration tests for this [API_ENDPOINT|WORKFLOW].

Code under test:

Terminal
[CODE]

Test environment:

  • Framework: [TEST_FRAMEWORK]
  • Database: [TEST_DB_APPROACH]
  • External services: [MOCKED|REAL]

Scenarios to test:

  1. [SCENARIO_1]
  2. [SCENARIO_2]
  3. [SCENARIO_3]

Setup/teardown requirements: [SETUP_REQUIREMENTS]

Terminal

## Creating Your Own Templates

### Template Design Process

1. **Identify repetition** - What prompts do you write often?
2. **Extract variables** - What changes between uses?
3. **Define fixed elements** - What stays the same?
4. **Add optional sections** - What's sometimes needed?
5. **Test and refine** - Iterate based on results

### Template Naming Convention

[TASK_TYPE][SPECIFICITY][VARIATION]

Examples:

  • generate_function_typescript
  • debug_error_runtime
  • review_security_api
  • refactor_extract_component
Terminal

### Template Storage

Options for storing templates:
- **IDE snippets** - Quick access while coding
- **Text expander** - System-wide availability
- **Git repository** - Team sharing and version control
- **Documentation site** - Searchable reference

## Combining Templates

Chain templates for complex workflows:

Step 1: Use "generate_function" template Step 2: Use "generate_tests" template for the function Step 3: Use "review_code" template on both

Terminal

## Practice Exercise

Create templates for your common tasks:

1. **Identify** 3 prompts you write frequently
2. **Extract** the variable and fixed parts
3. **Format** as reusable templates
4. **Test** with different inputs
5. **Refine** based on output quality

## Summary

- Templates provide consistency, speed, and quality
- Include clear placeholders for variable content
- Build templates for your most common tasks
- Share templates with your team
- Continuously refine based on results

## Next Steps

Let's explore common mistakes in prompt engineering—patterns to avoid and how to fix them.
Mark this lesson as complete to track your progress