Claude Code Advanced Prompting Techniques
Basic prompting gets you answers. Advanced prompting gets you the right answers — faster, with less back-and-forth, and in exactly the format your project needs. This topic covers techniques that experienced developers use to get consistently high-quality output from Claude Code.
The Difference Between Basic and Advanced Prompts
BASIC PROMPT: "Write a login function" ADVANCED PROMPT: "Write a login function in TypeScript for a Next.js app. Use bcrypt for password comparison, return a JWT token on success, and throw a typed error on failure. The user model has: id (uuid), email (string), passwordHash (string). Do not use any, use proper return types."
The basic prompt forces Claude to make assumptions. Every assumption it makes might be wrong for your project. The advanced prompt eliminates assumptions and gets you code you can use immediately.
Technique 1 — Role Assignment
Telling Claude to act as a specific type of expert changes the lens it uses to respond. The same question gets a different answer depending on the role you assign.
Same question, different roles: ────────────────────────────────────────────── "You are a security engineer. Review this API endpoint." → Focuses on authentication gaps, injection risks, exposed data "You are a performance engineer. Review this API endpoint." → Focuses on slow queries, caching opportunities, payload size "You are a senior developer mentoring a junior. Explain this code." → Focuses on teaching, explains why not just what
How to Write a Role Prompt
"Act as a [role] with expertise in [domain]. Your task is to [specific task]. Prioritize [what matters most]." Example: "Act as a database architect with expertise in PostgreSQL. Your task is to design a schema for an e-commerce platform. Prioritize query performance for the product search feature."
Technique 2 — Chain of Thought Prompting
Chain of thought means asking Claude to think through a problem step by step before giving the final answer. This reduces errors on complex tasks because Claude verifies its own reasoning before committing to an output.
WITHOUT chain of thought: "Is this database schema normalized correctly?" → Claude jumps to an answer that might miss subtle issues WITH chain of thought: "Is this database schema normalized correctly? Think through each normal form step by step before giving your final verdict." → Claude checks 1NF, then 2NF, then 3NF systematically
Add phrases like "think step by step", "reason through this before answering", or "show your work" to trigger this behavior.
Chain of Thought for Debugging
"This function returns the wrong total. Here is the code and here is the input/output: Input: [1, 2, 3] → Expected: 6, Got: 5 Walk through the function line by line with the actual input values before identifying the bug."
Claude traces the execution with real values, spots exactly where the result goes wrong, and explains the fix clearly.
Technique 3 — Few-Shot Prompting
Few-shot prompting means giving Claude one or two examples of the output you want before asking it to produce the real thing. This is especially powerful when you need code in a specific style that is unique to your project.
"Write error handling for the getUserById function.
Follow the same pattern as these existing functions:
Example 1 (getProductById):
async function getProductById(id: string) {
try {
const product = await db.product.findUnique({ where: { id } });
if (!product) throw new AppError("Product not found", 404);
return product;
} catch (err) {
if (err instanceof AppError) throw err;
throw new AppError("Database error", 500);
}
}
Example 2 (getOrderById):
[paste second example]
Now write getUserById following the same pattern."
Claude reads the pattern from your examples and matches it exactly — the same error class names, the same structure, the same type annotations. This is far more reliable than describing the pattern in words.
Technique 4 — Constraint Prompting
Constraints tell Claude what it must not do. Without constraints, Claude picks the most common solution, which may not fit your project's specific requirements.
Common constraints to add: ────────────────────────────────────────────────────── "Do not use any external libraries — only standard library" "Do not modify the function signature" "Keep the function under 30 lines" "Do not use recursion — use iteration instead" "This must work in Node.js 16 — do not use ES2023 features" "Do not change the database schema" "Write this without using async/await — use Promise chains"
Constraint Prompt Example
"Refactor this sorting function to be more readable. Constraints: - Keep the same Big-O time complexity (O n log n) - Do not change the function name or parameters - No external libraries - Must work in Internet Explorer 11 (no arrow functions) [paste your function]"
Technique 5 — Output Format Specification
Telling Claude exactly what format to use for the output saves you from reformatting everything manually. You can request specific structures, lengths, and styles.
Format examples: ────────────────────────────────────────────────── "Return only the code, no explanation" "Return the code, then a bullet list of trade-offs" "Format as a markdown table with columns: Issue, Severity, Fix" "Return JSON only — no code block wrappers" "Give me three different approaches, label them Option A/B/C" "Explain each line with an inline comment"
Format Prompt for Code Reviews
"Review this code and return findings in this exact format: ISSUE: [short title] SEVERITY: [High/Medium/Low] LINE: [line number] PROBLEM: [one sentence explanation] FIX: [one sentence suggestion] --- List all findings, one block per issue."
With a specified format, you can copy Claude's output directly into a code review tool or share it with a teammate without editing it.
Technique 6 — Iterative Prompting
Iterative prompting means building the output in stages rather than asking for everything at once. Start with structure, then add detail, then refine. Each step is a small, clear request.
STAGE 1: "Design the high-level structure of a shopping cart
class — just the method names, no implementation."
↓
STAGE 2: "Now implement just the addItem method."
↓
STAGE 3: "Now implement removeItem, following the same
pattern as addItem."
↓
STAGE 4: "Now add input validation to all methods."
↓
STAGE 5: "Now write unit tests for the class."
Each stage builds on the confirmed output of the previous one. You catch mistakes early — after Stage 1 — instead of after Claude writes 200 lines of code in the wrong direction.
Technique 7 — Context Seeding
Context seeding means giving Claude a snapshot of your project's key facts before asking your question. This replaces multiple clarification rounds with one thorough opener.
Context Seed Template: ────────────────────────────────────────────────── Project: [name and purpose] Language: [language and version] Framework: [main framework] Database: [database and ORM] Key conventions: [your project's important rules] Current task: [what you need today] Relevant code: [paste only the relevant piece] Question: [your actual question]
Example Seeded Prompt
"Project: B2B SaaS billing platform Language: TypeScript 5.2 (strict mode) Framework: NestJS with class-validator Database: PostgreSQL with TypeORM Convention: All services use Result type (no throwing) Current task: Add a method that applies a promo code to an invoice. Relevant code: [paste Invoice entity and InvoiceService skeleton] Question: Write the applyPromoCode method following our conventions."
Technique 8 — Negative Examples
Sometimes the clearest way to tell Claude what you want is to show it what you do not want. Negative examples eliminate the most common wrong answers before Claude even starts.
"Write a function to validate a US phone number.
Do NOT use a single giant regex — break it into
readable steps.
Do NOT throw exceptions — return a validation result object.
Do NOT accept international formats — US only.
Here is an example of what NOT to do:
function validate(phone) {
return /^\+?1?\d{10}$/.test(phone); // too simple, too opaque
}
Now write the correct version."
Technique 9 — Ask Claude to Critique Its Own Output
After Claude gives you an answer, ask it to review its own work. Claude often catches things in self-review that it missed on the first pass.
Prompt after receiving output: "Now critique what you just wrote. What are the weaknesses, edge cases it misses, or better ways to approach this?"
This two-pass approach — generate, then critique — produces noticeably better code than a single prompt, especially for complex logic.
Combining Techniques
Advanced prompting is most powerful when you combine multiple techniques in a single prompt.
Combined technique example: ────────────────────────────────────────────── Role: "You are a TypeScript expert." Context seed: [Project facts] Chain of thought: "Think step by step." Constraint: "No any types, no libraries." Format: "Return code then a risk list." Question: "Write the payment processor."
Key Points
- Role assignment changes Claude's perspective — security engineer, performance engineer, and mentor roles give different answers to the same question
- Chain of thought prompting reduces errors on complex tasks — ask Claude to reason step by step before answering
- Few-shot prompting gives Claude examples of your specific style — it matches patterns more reliably than descriptive instructions
- Constraint prompting tells Claude what not to do — this is often clearer than describing what to do
- Iterative prompting breaks large tasks into stages — you catch direction mistakes after stage one instead of after 200 lines
- Ask Claude to critique its own output — a two-pass approach produces better results than a single prompt
