Effective Prompting for Code

Building Your Prompt Library

4 min read

A personal prompt library saves time and ensures consistency. This lesson provides ready-to-use templates for common development tasks.

Why Build a Prompt Library?

Benefits:
├── Consistency across projects
├── Time savings (no reinventing)
├── Quality baseline (tested prompts)
├── Team sharing capabilities
└── Continuous improvement

Core Templates

1. Code Generation

Function Creation

Create a [language] function named [functionName]:

Purpose: [what it does]

Parameters:
- [param1]: [type] - [description]
- [param2]: [type] - [description]

Returns: [type] - [description]

Requirements:
- Handle edge cases: [list cases]
- Throw errors for: [conditions]
- Include JSDoc/docstring

Example usage:
[show expected input/output]

Match the style in: @[reference file]

Class Creation

Create a [language] class named [ClassName]:

Purpose: [responsibility]

Properties:
- [prop1]: [type] - [description]

Methods:
- [method1]([params]): [returnType] - [description]

Design patterns:
- [pattern to follow]

Implement interfaces:
- [interface names]

Reference: @[similar class file]

2. Testing

Unit Test

Write unit tests for @[file path]:

Test framework: [Jest/Vitest/pytest/etc]
Coverage target: [percentage or specific functions]

Test cases needed:
- Happy path: [scenarios]
- Edge cases: [scenarios]
- Error cases: [scenarios]

Mocking requirements:
- [what to mock and how]

Follow patterns in: @[existing test file]

Integration Test

Write integration tests for @[feature/endpoint]:

Test framework: [framework]
Setup requirements: [database seeding, auth, etc]

Scenarios:
1. [Scenario name]
   - Given: [precondition]
   - When: [action]
   - Then: [expected result]

2. [Next scenario]

Cleanup: [what to clean up after tests]

3. Refactoring

Extract Function

In @[file path], extract the logic at lines [X-Y] into a separate function:

Function name: [suggested name]
Purpose: [why extracting]

Ensure:
- No change in behavior
- Proper error handling transferred
- Tests still pass
- Add new tests if needed for extracted function

Improve Code Quality

Refactor @[file path] to improve:

Issues to address:
- [Issue 1]: [description]
- [Issue 2]: [description]

Maintain:
- Existing public API
- All test coverage
- Backward compatibility

Do not:
- Change unrelated code
- Add new features
- Remove functionality

4. Bug Fixing

Debug Template

Bug report for @[file path]:

Observed behavior: [what happens]
Expected behavior: [what should happen]
Reproduction steps:
1. [step 1]
2. [step 2]

Error message (if any):

[error output]


Related logs:

[relevant logs]


Investigate and provide:
1. Root cause analysis
2. Fix implementation
3. Test case to prevent regression

5. Documentation

Code Documentation

Add documentation to @[file path]:

Style: [JSDoc/TSDoc/docstrings]

Document:
- All exported functions
- Complex logic blocks
- Public class methods
- Type definitions

Include:
- Parameter descriptions
- Return value descriptions
- Usage examples
- Edge case notes

README Template

Create/update README.md for @[project/directory]:

Include sections:
- Overview (what it does)
- Installation
- Quick start
- Configuration options
- API reference (if applicable)
- Examples
- Contributing guidelines
- License

Keep it concise but complete.

6. API Development

REST Endpoint

Create a REST endpoint:

Route: [METHOD] /api/[path]
Auth: [none/session/JWT/API key]

Request:
- Headers: [required headers]
- Query params: [params]
- Body schema:
```json
{
  "field": "type"
}

Response:

  • Success (200):
{
  "data": {}
}
  • Errors: [list status codes and meanings]

Validation:

  • [validation rules]

Rate limiting: [if applicable]

Follow pattern: @[existing route file]


#### GraphQL Resolver

Create a GraphQL resolver for:

Type: [Query/Mutation/Subscription] Name: [resolver name]

Schema:

type [TypeName] {
  [fields]
}

Arguments: [input types] Returns: [return type]

Business logic:

  • [logic step 1]
  • [logic step 2]

Error handling:

  • [error scenarios and messages]

### 7. Database

#### Migration

Create a database migration:

Purpose: [what change]

Schema changes:

  • Add table: [name] with columns [list]
  • Modify column: [table.column] [change]
  • Add index: [name] on [table(columns)]

Data migration: [if needed]

Rollback strategy: [how to reverse]

ORM: [Prisma/TypeORM/Drizzle/etc]


#### Query Optimization

Optimize the query in @[file:line]:

Current issues:

  • [issue 1]
  • [issue 2]

Expected data volume: [rows/records] Performance target: [ms/queries per second]

Consider:

  • Indexing opportunities
  • Query restructuring
  • Caching strategy
  • Pagination if needed

### 8. Security

#### Security Review

Security review for @[file or feature]:

Check for:

  • Input validation
  • SQL/NoSQL injection
  • XSS vulnerabilities
  • CSRF protection
  • Authentication bypass
  • Authorization issues
  • Sensitive data exposure
  • Rate limiting

Context:

  • [relevant context about the code]

Provide:

  • Findings with severity
  • Specific fix recommendations
  • Code examples for fixes

## Organization Strategies

### File Structure

prompts/ ├── generation/ │ ├── functions.md │ ├── components.md │ └── classes.md ├── testing/ │ ├── unit.md │ └── integration.md ├── refactoring/ │ ├── extract.md │ └── improve.md ├── debugging/ │ └── investigate.md ├── documentation/ │ ├── code.md │ └── readme.md └── project-specific/ └── [project-name].md


### Using Variables

Create prompts with placeholders:

```markdown
# Function Creation Template

Create a {{LANGUAGE}} function named `{{FUNCTION_NAME}}`:

**Purpose:** {{PURPOSE}}

**Parameters:**
{{#each PARAMETERS}}
- `{{name}}`: `{{type}}` - {{description}}
{{/each}}

**Returns:** `{{RETURN_TYPE}}` - {{RETURN_DESCRIPTION}}

Integration with Tools

Cursor

Save as snippets in .cursorrules:

When creating API routes, follow this template:
[paste template]

Claude Code

Create a prompts config:

// .claude/prompts.json
{
  "templates": {
    "api-route": "prompts/generation/api-route.md",
    "unit-test": "prompts/testing/unit.md"
  }
}

Maintaining Your Library

Version Control

# Keep prompts in git
git add prompts/
git commit -m "Add API route generation template"

Improvement Loop

1. Use a template
2. Note what worked/didn't
3. Update template
4. Commit improvement
5. Repeat

Team Sharing

prompts/
├── team/           # Shared team templates
├── personal/       # Your personal templates
└── project/        # Project-specific templates

Library Wisdom: Start with 5-10 templates for your most common tasks. Grow the library organically as you discover patterns. Quality over quantity—one excellent template is better than ten mediocre ones.

You now have a foundation for effective prompting. In Module 5, we'll learn how to debug AI-generated code. :::

Quiz

Module 4: Effective Prompting for Code

Take Quiz