Module 1 · Prompt Foundations · Lesson 2 of 18
Anatomy of a Strong Developer Prompt: Context, Specificity, Constraints and Output Format
Find the requirement the generated parser missed
A CSV prompt specifies money, culture, UTC handling and malformed-input behavior. Inspect the two candidate implementations against every rule.
- Read the original prompt fixtures and the complete comparison below.
- Predict the printed totals and timestamp before running.
- Answer the question, then use Try it → Run for the complete program. Test a counterexample separately in a copy; the generated parser is intentionally incomplete.
Before
Write a C# method that sums the order totals in a CSV file.
Illustrative candidate — member fragment, intended to sit inside a type. It is not a standalone program:
public static double Total(string[] lines) => lines.Sum(l => double.Parse(l.Split(',')[1]));After
Context: .NET 8 console tool, C# 12, nullable enabled. Runs on build agents in several countries. Task: write a parser and a total for order lines. Input line format: Id,Amount,PlacedAt e.g. A-100,1234.50,2026-10-01T09:30:00+05:30 Rules: - Amount is money: use decimal, never double. Amounts always use '.' as the decimal separator. - PlacedAt has an offset; store it as UTC. - A malformed line throws FormatException that includes the line. Constraints: no NuGet packages, no regex. Output: one file with a record Order, Parse(string) and Total(IEnumerable<string>). Then list your assumptions.
The complete BCL-only program below compares both candidates using German current culture. Run it as Program.cs in a .NET 10 console project with implicit usings enabled, or use the verified Try it control. The retained prompts name their original .NET 8 / C# 12 target; the “After” candidate deliberately does not satisfy every rule. No model service or NuGet package is used by this program:
using System.Globalization;
// The same task, two prompts. "Before" is what a vague prompt typically returns; "After" follows the specific prompt.
var lines = new[] { "A-100,1234.50,2026-10-01T09:30:00+05:30", "A-101,99.99,2026-10-01T23:10:00+05:30" };
CultureInfo.CurrentCulture = new CultureInfo("de-DE"); // a developer laptop or build agent in Germany
Console.WriteLine($"Before (double, current culture): total = {Before.Total(lines)}");
Console.WriteLine($"After (decimal, invariant): total = {After.Total(lines).ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"After first order date (UTC): {After.Parse(lines[0]).PlacedAtUtc:O}");
static class Before
{
// Output of: "write a C# method that sums the order totals in a CSV"
public static double Total(string[] lines) => lines.Sum(l => double.Parse(l.Split(',')[1]));
}
static class After
{
// Output of the specific prompt: decimal money, invariant culture, DateTimeOffset kept as UTC, errors name the line.
public sealed record Order(string Id, decimal Amount, DateTimeOffset PlacedAtUtc);
public static Order Parse(string line)
{
var parts = line.Split(',');
if (parts.Length != 3) throw new FormatException($"Expected 3 fields but got {parts.Length}: '{line}'");
try
{
var amount = decimal.Parse(parts[1], NumberStyles.Number, CultureInfo.InvariantCulture);
var placed = DateTimeOffset.Parse(parts[2], CultureInfo.InvariantCulture).ToUniversalTime();
return new Order(parts[0], amount, placed);
}
catch (Exception e) when (e is FormatException or OverflowException or ArgumentException)
{
throw new FormatException($"Invalid order line: '{line}'", e);
}
}
public static decimal Total(IEnumerable<string> lines) => lines.Select(Parse).Sum(o => o.Amount);
}Check the decision
Which next test targets the unimplemented offset requirement?
Show answer
Correct answer: B
The two valid examples cannot establish rejection of an omitted offset. DateTimeOffset.Parse can supply a local offset; successful parsing does not enforce the prompt.
Option A: Another explicit-offset timestamp repeats the accepted path instead of testing the missing-offset rejection requirement.
Option C: Changing presentation does not exercise the invalid input the requirement says to reject.
Option D: The numeric type change does not test whether a timestamp omitted its required offset.
Hint: Look for an input that violates a named requirement.
Trace and explain
| Observation or case | Check your reasoning |
|---|---|
| German-culture draft | Trace which separator the selected culture recognizes. |
| Invariant decimal sample | Calculate the total independently, then compare your run. |
| Missing offset | Test rejection against the stated timestamp contract. |
Interview rehearsal: explain the result in 60–90 seconds. Name the boundary that owns the rule and one nearby case your evidence has not covered.
Reference and worked examples
Intuition
A prompt is a ticket you hand to a fast colleague who has never seen your codebase. A good ticket says what is wanted, why, what the definition of done is, and what must not change. Gaps in the ticket can invite guesses, but even a complete prompt can produce errors and still needs verification.
Use this checklist to make the task reviewable:
Context + Task + Relevant code + Constraints + Expected output
Read the diagram: Real interfaces, rules and acceptance checks reduce unsupported assumptions. A specified prompt still needs execution and review.
Context: app type, .NET version, packages, architecture → promptTask: one verb, one artifact (fix, write, review, explain) → promptRelevant code: real types and signatures, the error → promptConstraints: business rules, what must not change, no new packages → promptExpected output: files by name, tests, format, length → promptprompt → answer you can check
Deep dive
1. Context: the facts the model cannot know
| Tell it | Why it changes the answer |
|---|---|
| App type (Web API, minimal API, worker, Blazor, console, library) | Hosting model, DI, lifetime and error handling differ |
| Target framework and language version (".NET 8, C# 12") | Available APIs (TimeProvider, primary constructors, collection expressions) |
| Data access (EF Core 8, Dapper, raw ADO.NET) and database | Query patterns, transactions, SQL dialect |
| Architecture (layered, Clean Architecture, vertical slices) | Where code goes and which project references which |
| Test stack (xUnit, NSubstitute, Moq, Testcontainers) | What the test code looks like |
Conventions (nullable enabled, warnings as errors, sealed by default) | Small things that otherwise cost review time |
On supported tools, keep stable project facts in a repository instructions file, covered in Lesson 3. Check that the relevant surface actually loads it.
2. Task: one verb, one artifact
Name the outcome and artifact: an endpoint, EF Core query, xUnit theory or explanation. For example, replace “help with orders” with “find the cause of this failed order test.” Number related steps; split independent tasks when that makes scope and review clearer.
3. Specificity: replace adjectives with facts
The weakest words in developer prompts are adjectives: fast, clean, secure, robust, production-ready. Replace each with something checkable:
| Vague | Specific |
|---|---|
| make it fast | p95 under 50 ms for 10,000 rows; no per-row database call |
| make it secure | caller must be authorized for the order; derive tenant identity from validated authentication, not a caller-supplied body field |
| handle errors | invalid input returns 400 problem details; duplicate email returns 409 |
| production-ready | nullable-clean, cancellation tokens passed through, logs contain no PII |
| clean code | match the style of the attached InvoiceService.cs |
4. Constraints: what must not happen
State boundaries explicitly, then verify the diff respects them:
- "Do not add NuGet packages."
- "Keep the public signature unchanged."
- "Do not change behavior; list anything that would change."
- "Use
decimalfor money andInvariantCulturefor parsing." - "Do not touch files other than X."
Pair a restriction with the intended alternative when useful: “inject TimeProvider for this service’s clock.” Wording guides the assistant; it does not enforce the boundary.
5. Expected output: make the answer checkable
Ask for the shape you will review:
- code by file name, only changed members, or a unified diff;
- a list of assumptions it made;
- tests that exercise the rules and meaningful failure cases;
- a short "what could break" section;
- a length limit for explanations ("at most 5 bullets").
Roles and personas
A role can suggest a review focus, but it does not establish expertise or correctness. “Review authorization and injection risks” is clearer than “act as an expert.” Supply the relevant code and acceptance checks either way.
Ask for questions when the gap is real
For bigger tasks, request a small number of questions about essential gaps. For routine implementation choices, ask for stated assumptions and progress. Ownership, access and business rules need evidence; a confident guess is not a substitute.
Code example: one request, two prompts
Use the two prompt fixtures and complete comparison shown before the question.
After predicting, run the complete program and record the two totals and UTC timestamp. Then test a malformed row and a missing-offset timestamp in a copy. A successful happy-path run does not establish the full parser contract.
- Compare the two parsing cultures and independently calculate the intended money total.
- Trace timestamp parsing separately from conversion to UTC.
- The second prompt states number type, culture, time handling and error behavior. Check each requirement independently.
- These are authored candidates; the comparison does not prove that a particular prompt will make a model produce this code.
The improved parser still needs a contract review
Keep the deliberately incomplete parser as a review exercise:
Split(',')does not support quoted fields, embedded commas or multiline CSV.- The sample assumes non-null lines and does not validate the identifier.
NumberStyles.Numberaccepts more than a strict digits-and-decimal-point grammar. Decimal conversion can round excessive precision; range and scale rules are absent.DateTimeOffset.Parsecan supply a local offset when one is missing. Define the accepted timestamp format and test explicit-offset rejection separately.- The exception includes the full synthetic row. Real records need a safe line number/error category and controlled, redacted diagnostics where appropriate.
Better prompt specifications reduce ambiguity; they do not prove the implementation follows every rule.
Failure modes
- Unfocused context. Extra files can obscure relevant evidence. Start with the affected code and expand when needed.
- Hidden business rules. The model writes CRUD fast, but "email must be unique" or "premium discount applies at 1000 or more" is only in your head.
- Unclear task boundaries. Number related steps and define completion checks; separate independent work when helpful.
- Adjectives instead of numbers. "Fast" and "secure" get generic advice.
- No output shape. You get a wall of prose and code that is hard to review.
- Role without facts. "Act as an expert" plus "fix this" still forces the model to guess.
Interview angle
Example: request a CSV parser.
- Specify the real input grammar, money type/culture and timestamp policy.
- State error handling, privacy constraints and allowed dependencies.
- Request a focused diff, assumptions and tests for both valid and invalid inputs.
- Review the generated parser against every rule; passing two examples is limited evidence.
Practice questions
- Rewrite "make this endpoint secure" as a specific constraint for a multi-tenant API.
Answer: For example: "Use the tenant identifier from an authenticated principal whose issuer, audience and claims mapping have been validated for this application, not an arbitrary token or body field. Enforce tenant scope and the caller's resource permissions. Under our disclosure policy, use a consistent 404 response for missing or inaccessible orders." The claim name and 404-versus-403 policy are application-specific, and a status code alone does not eliminate all information leaks.
- Why is
double.Parse(text)without a culture risky in code that runs on many machines?
Answer: It uses the current culture, so the same separator can mean a decimal point or a grouping separator. Choose decimal for money and an explicit culture and accepted-input policy; verify the sample under both cultures.
- When is a role ("act as a security reviewer") genuinely useful?
Answer: When it changes the lens of the answer, for example toward authorization and injection risks. It does not replace context such as versions, code and rules.
- What output format would you request for a refactor of a 300-line class?
Answer: Only the changed members or a unified diff, a list of behavior changes (ideally "none"), assumptions, and tests that pin current behavior.
- How do you stop an assistant from asking ten questions before writing anything?
Answer: Allow a small number of questions only when information is essential, and otherwise ask it to state assumptions and continue.
Related on TechInterviewNotes
- Previous lesson: How AI Coding Assistants Read Your Prompt
- Next lesson: Giving the Assistant Code Context
TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·