How to Write Prompts for Coding Tasks

Get better code from AI — 20 patterns with before/after

Ad placeholder (leaderboard)

Why coding prompts are different

A prompt for an essay can be loose because there are many acceptable answers. Code has to compile, pass tests, and match an existing codebase, so the prompt has to be precise. The model has no access to your repository, your runtime, or the error you are staring at — it only knows what you put in the prompt window. Most “the AI gave me bad code” complaints are really “I gave the AI bad context” complaints. Get the inputs right and the output improves dramatically.

The builder below assembles a clean request from the parts that actually matter: the task, the language and version, the constraints, the existing code, and whether you want tests. Fill it in, copy the result, and paste it into any LLM.

How it works

Strong coding prompts share a structure. First, the goal — one plain sentence: “Write a function that deduplicates a list of records by email, keeping the most recent.” Second, the environment — language, version, and allowed dependencies, because the model will otherwise reach for whatever is popular. Third, the constraints — performance limits, style rules, error handling expectations. Fourth, the existing code — paste the type definitions and surrounding functions so the new code fits. Finally, the verification — ask for tests, or a usage example, so you can check the result without trusting it blindly.

The biggest leverage is the feedback loop. Generate, run, and when something fails, paste the exact error and the input that caused it back into the chat. Say “change as little as possible to fix this.” Models are excellent at the narrow fix and dangerous at the speculative rewrite, so keep the scope pinned.

Patterns and tips

  • Pin the version. “Python 3.11” or “Node 20, ESM, TypeScript strict” stops the model from using syntax your runtime rejects.
  • Forbid surprise dependencies. Add “standard library only” or list the exact packages allowed. This alone removes most build failures.
  • Ask for tests first for tricky logic. “Write failing tests for these edge cases, then the implementation that passes them” produces more correct code than asking for the implementation alone.
  • Give it the error verbatim. Stack traces contain the answer; do not paraphrase them. Include the line that threw and the input value.
  • Use “minimal change.” When fixing, explicitly forbid refactoring working code so you do not trade one bug for two.
  • Request an explanation only on demand. Generate code, then ask “explain the regex on line 4” rather than asking for a tutorial every time.
Ad placeholder (rectangle)