Writing Prompts That Get Better Code

Writing Prompts That Get Better Code

Writing Prompts That Get Better Code

Most disappointing AI output isn't a model failure. It's a briefing failure. You asked a vague question and got a vague answer that happened to be wrapped in confident syntax.

The good news: a few concrete habits fix the majority of it. None of them are clever tricks. They're just the same things that make a request to a human colleague clear.

1. Give context before the ask

Compare these two prompts:

Write a function to format dates.

Write a function to format an ISO date string as "July 24, 2026" for display in a blog list. It runs in the browser, dates may be missing or malformed, and it should return an empty string rather than throw.

The second one produces something you can actually ship. The model isn't guessing your environment, your input shape, or your failure behavior; you told it.

2. State the constraints out loud

Constraints are not restrictions on the model; they're information. Spell out the ones that matter:

  • No new dependencies, or use library X.
  • Which runtime, browser, or version.
  • Performance or size limits.
  • The style or patterns the surrounding code uses.

If you don't name a constraint, don't be surprised when the answer violates it. The model can't read the rest of your codebase's mind.

3. Show an example of "good"

One example of the shape you want is worth a paragraph of description. If you want results in a particular format, show a sample. If new code should match an existing pattern, paste a snippet of that pattern:

// Match this style for the new endpoints:
export async function getUser(id) {
  const res = await db.query('SELECT * FROM users WHERE id = $1', [id]);
  return res.rows[0] ?? null;
}

Now "add a getPost function" has an unambiguous target.

4. Ask for the reasoning on hard calls

For anything with a real design decision, ask the model to explain its approach before it writes the final version. This does two things: it catches flawed assumptions early, and it gives you something to push back on.

Before writing it, list two ways to handle pagination here and the trade-offs. Then implement the one that avoids loading everything into memory.

5. Iterate in small requests

A giant prompt that asks for eight things produces eight mediocre things. Smaller, sequential requests let you steer:

  1. "Draft the data model."
  2. "Now the read path."
  3. "Now handle the empty and error states."

Each step is easy to verify, and mistakes don't cascade.

The one-sentence version

Tell it what you'd tell a sharp new teammate: the goal, the constraints, an example of good, and where the tricky decision is. Do that, and the quality of what comes back stops feeling random.

A vague prompt is a coin flip. A specific one is a collaboration.


Want the workflow this fits into? See How I Actually Work With AI Coding Agents.