본문으로 건너뛰기 AI Prompt Engineering for Developers | ChatGPT

AI Prompt Engineering for Developers | ChatGPT

AI Prompt Engineering for Developers | ChatGPT

이 글의 핵심

AI Prompt Engineering for Developers. Learn how to craft prompts that generate optimal code in ChatGPT, Claude, and Cursor. Master Few-shot, Chain-of-Thought, role prompting, and more practical patterns.

Introduction

Prompt engineering is the skill of designing questions to get desired results from AI. With the same AI, results can differ by 10x or more depending on the prompt. To put it in perspective, a bad prompt is “make something for me”, while a good prompt is “Create a TODO app with React + TypeScript that supports dark mode and style it with Tailwind CSS”.

What You’ll Learn

  • How to write effective prompts
  • Understanding advanced patterns like Few-shot and Chain-of-Thought
  • Identifying optimal prompts for different development scenarios
  • Learning tool-specific strategies for different AI tools

Reality in Practice

When learning development, everything seems clean and theoretical. But practice is different. You wrestle with legacy code, chase tight deadlines, and face unexpected bugs. The content covered in this article was initially learned as theory, but it was through applying it to actual projects that I realized “Ah, this is why it’s designed this way.” What stands out in my memory is the trial and error from my first project. I did everything by the book but couldn’t figure out why it wasn’t working, spending days struggling. Eventually, through a senior developer’s code review, I discovered the problem and learned a lot in the process. In this article, I’ll cover not just theory but also the pitfalls you might encounter in practice and how to solve them.

Table of Contents

  1. Prompt Basics
  2. Core Patterns
  3. Use Case Prompts
  4. Tool-Specific Strategies
  5. Advanced Techniques
  6. Real Examples
  7. Troubleshooting
  8. Conclusion

Prompt Basics

Bad Prompt vs Good Prompt

Bad Prompt:

"Create a login"

Problems:

  • Language/framework unclear
  • Insufficient requirements
  • No style guide Good Prompt:
"Implement a login page with Next.js 14 App Router.
Tech Stack:
- TypeScript
- React Hook Form
- Zod (validation)
- Tailwind CSS
Requirements:
1. Email/password input
2. Real-time validation (email format, password 8+ characters)
3. Loading state display
4. Error message display
5. Dark mode support
File: app/login/page.tsx
"

Prompt Structure (5W1H)

1. Who (Role)

"You are a senior full-stack developer."

2. What (What to do)

"Design and implement a RESTful API."

3. Why (Purpose)

"To build a user authentication system."

4. Where (Environment)

"In a Node.js + Express + PostgreSQL environment"

5. When (Timing)

"When a user signs up"

6. How (Method)

"Using JWT token-based authentication, hashing passwords with bcrypt"

Core Patterns

1. Zero-shot (No Examples)

Definition: Direct request without examples

"Implement a binary search function in Python"

Pros: Fast
Cons: Lower accuracy

2. Few-shot (With Examples)

Definition: Provide examples to learn patterns

"Create API responses in the following format:
Example 1 (Success):
{
  "success": true,
  "data": { "id": 1, "name": "John" },
  "error": null
}
Example 2 (Failure):
{
  "success": false,
  "data": null,
  "error": { "code": "NOT_FOUND", "message": "User not found" }
}
Now create a response format for a product lookup API."

Pros: Higher accuracy
Cons: Longer prompts

3. Chain-of-Thought (Step-by-Step Thinking)

Definition: Guide AI to think step by step

"Solve the following problem step by step:
Problem: Remove duplicates and sort the array [3, 1, 4, 1, 5, 9, 2, 6]
Steps:
1. Choose duplicate removal method
2. Choose sorting algorithm
3. Analyze time complexity
4. Implement code
5. Write test cases
"

Result:

AI Response:
1. Duplicate removal: Use Set (O(n))
2. Sorting: Built-in sort (O(n log n))
3. Overall time complexity: O(n log n)
4. Code:
   def remove_duplicates_and_sort(arr):
       return sorted(set(arr))
5. Test:
   assert remove_duplicates_and_sort([3,1,4,1,5]) == [1,3,4,5]

4. Role Prompting (Role Assignment)

"You are a senior backend developer with 10 years of experience.
You prioritize security, performance, and scalability.
Design the following API:
- User authentication
- Permission management
- Logging
- Error handling
"

5. Constraint Prompting (Constraints)

"Write code following these constraints:
Required:
- Use TypeScript
- Minimize external libraries
- JSDoc comments for all functions
- Include unit tests
Prohibited:
- Using any type
- Using console.log
- Using global variables
"

Use Case Prompts

1. Implementing New Features

Prompt:

"Implement an infinite scroll component with React + TypeScript.
Requirements:
- Use Intersection Observer API
- Display loading state
- Error handling
- Separate into custom hook
- Support generic types
Example usage:
const { data, loading, error } = useInfiniteScroll<Post>(
  '/api/posts',
  { limit: 20 }
);
File structure:
- hooks/useInfiniteScroll.ts
- components/InfiniteScrollList.tsx
"

2. Bug Fixing

Prompt:

"Find and fix the bug in the following code:
[Paste code]
Error message:
TypeError: Cannot read property 'length' of undefined
Steps:
1. Analyze bug cause
2. Explain fix method
3. Provide fixed code
4. Add test cases
"

3. Refactoring

Prompt:

"Refactor the following code:
[Paste code]
Improvements:
1. Function separation (Single Responsibility Principle)
2. Strengthen type safety
3. Add error handling
4. Performance optimization
5. Improve readability
Include explanations for each change.
"

4. Code Review

Prompt:

"Review the following code:
[Paste code]
Review perspectives:
1. Security vulnerabilities (OWASP Top 10)
2. Performance issues
3. Code smells
4. Best practice violations
5. Test coverage
Provide specific examples and improvement suggestions for each item.
"

5. Writing Test Code

Prompt:

"Write test code for the following function:
[Function code]
Test framework: Jest + React Testing Library
Test cases:
1. Normal operation
2. Edge cases (empty array, null, undefined)
3. Error cases
4. Async handling
5. Mocking when needed
Add explanatory comments to each test.
"

Tool-Specific Strategies

ChatGPT / Claude (Chat)

Advantages:

  • Long conversation context
  • Complex explanations possible Strategy:
Step 1: Big picture
"Design a blog system architecture"
Step 2: Specification
"Write the Prisma schema for the User model"
Step 3: Implementation
"Implement the signup API"
Step 4: Improvement
"Add email duplicate check and password hashing"

Cursor (Editor Integration)

Advantages:

  • Full project context
  • Multi-file editing Strategy:
Using @filename:
"@app.py @models.py Connect these two files
and add user authentication functionality"
Using @foldername:
"@src/components/ Add dark mode support
to all components"
Using @docs:
"@docs Refer to Next.js 14 App Router documentation
to implement dynamic routing"

GitHub Copilot (Autocomplete)

Advantages:

  • Fast line-level completion
  • Comment-based generation Strategy:
// Write detailed comments
// TODO: Filter only active users from user array,
// sort by name, and return email list function
function getActiveUserEmails(users) {
  // Press Tab for AI to implement
  return users
    .filter(user => user.isActive)
    .sort((a, b) => a.name.localeCompare(b.name))
    .map(user => user.email);
}

Advanced Techniques

1. Iterative Refinement

1st: "Create a TODO app with React"
→ Basic implementation
2nd: "Add localStorage save functionality"
→ Add persistence
3rd: "Add drag and drop reordering"
→ UX improvement
4th: "Add dark mode support"
→ Add theme

2. Context Compression

Summarize long code:

"Summarize the core logic of the following code:
[Long code]
Summary format:
- Input: ...
- Processing: ...
- Output: ...
- Time complexity: ...
"

3. Multimodal Prompts

Image + Text:

[Attach UI design image]
"Implement this design with React + Tailwind CSS.
Include responsive design."

4. Meta Prompts

Prompts that write prompts:

"When I request 'Create a React component',
write a prompt to get better results.
Information to include:
- Tech stack
- Requirements
- Constraints
- File structure
"

Real Examples

Example 1: REST API Design

Prompt:

"You are a senior backend developer.
Design and implement a RESTful API with the following requirements:
Project: Blog system
Tech stack: Node.js + Express + PostgreSQL + Prisma
Authentication: JWT
Entities:
1. User (id, email, password, name, createdAt)
2. Post (id, title, content, authorId, createdAt, updatedAt)
3. Comment (id, content, postId, authorId, createdAt)
API endpoints:
- POST /api/auth/register (signup)
- POST /api/auth/login (login)
- GET /api/posts (post list, pagination)
- POST /api/posts (create post, authentication required)
- GET /api/posts/:id (post detail)
- PUT /api/posts/:id (edit post, owner only)
- DELETE /api/posts/:id (delete post, owner only)
- POST /api/posts/:id/comments (create comment)
For each endpoint:
1. Prisma schema
2. Express router
3. Controller logic
4. Input validation (Zod)
5. Error handling
6. Example request/response
Please also provide file structure.
"

Example 2: Algorithm Optimization

Prompt:

"Optimize the following code:
def find_duplicates(arr):
    duplicates = []
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if arr[i] == arr[j] and arr[i] not in duplicates:
                duplicates.append(arr[i])
    return duplicates
Requirements:
1. Improve time complexity from O(n²) to O(n)
2. Space complexity analysis
3. Benchmark code before and after optimization
4. Explain each optimization technique
Test cases:
- [1, 2, 3, 4, 5] → []
- [1, 2, 2, 3, 3, 3] → [2, 3]
- [] → []
"

Example 3: Complex UI Component

Prompt:

"Create an advanced data table component with React + TypeScript.
Features:
1. Sorting (multiple columns)
2. Filtering (text, date range, selection)
3. Pagination (server-side)
4. Row selection (single, multiple)
5. Column hide/show
6. CSV export
7. Responsive (card view on mobile)
Tech:
- TanStack Table (React Table v8)
- Tailwind CSS
- React Hook Form (filters)
- Zod (validation)
File structure:
- components/DataTable/index.tsx
- components/DataTable/types.ts
- components/DataTable/hooks/useDataTable.ts
- components/DataTable/utils.ts
Provide the role and code for each file.
"

Troubleshooting

1. AI Generates Too Much Code

Problem:

Generates 1000 lines at once → Hard to read

Solution:

"Break the code into small units and explain.
Step 1: Type definitions only
Step 2: Utility functions only
Step 3: Main logic only
Step 4: Test code only
"

2. Context Loss

Problem:

Forgets initial requirements as conversation gets long

Solution:

Request periodic summaries:
"Summarize what we've implemented so far:
- Completed features
- Technologies used
- Remaining tasks
"

3. Inconsistent Code Style

Problem:

Generates code with different styles each time

Solution:

In project root .cursorrules or system prompt:
"""
Coding Style Guide:
Language: TypeScript (strict mode)
Framework: Next.js 14 App Router
Styling: Tailwind CSS
Linter: ESLint + Prettier
Rules:
- Prefer functional programming
- Use arrow functions
- async/await (no Promise.then)
- Explicit types (no any)
- JSDoc comments required
- Handle errors with try-catch
- No magic numbers (define as constants)
Naming:
- Components: PascalCase
- Functions/variables: camelCase
- Constants: UPPER_SNAKE_CASE
- Files: kebab-case
"""

Conclusion

Prompt engineering is an essential skill in the AI era. Key Summary:

  1. Be Specific: Specify tech stack, requirements, constraints
  2. Step by Step: Big picture → Specification → Implementation → Improvement
  3. Provide Examples: Improve accuracy with Few-shot
  4. Manage Context: Use @filename, @foldername Effective Prompt Checklist:
✅ Assign role (senior developer, security expert, etc.)
✅ Specify tech stack (language, framework, libraries)
✅ List requirements (features, constraints)
✅ Provide examples (input/output format)
✅ Present file structure
✅ Code style guide
✅ Test requirements

Practical Tips:


Frequently Asked Questions (FAQ)

Q. When would I use this in practice?

A. Complete guide to AI prompt engineering for developers.

Q. What should I read before this?

A. Follow the previous article or related articles links at the bottom of each post to learn in sequence.

Q. Where can I study this more deeply?

A. Check cppreference and the relevant library’s official documentation. The reference links at the end of the article are also worth using.


Other articles related to this topic.


Keywords Covered in This Article (Related Search Terms)

This article covers AI, PromptEngineering, ChatGPT, Claude, Cursor, Productivity.