Coding With AI

How to work with a coding assistant: giving it the right context, keeping each change small, using tests as the definition of done, and reviewing diffs.

14 minLesson 1 of 7
On this page
  1. The loop for one change
  2. What to put in the request
  3. Tests as the definition of done
  4. Reading the diff
  5. Choosing how to start a task
  6. Pitfalls: large changes, edited tests and long sessions
  7. Assistants that edit files and run commands
  8. Check yourself
  9. What to practise next

Working with an AI coding assistant means giving it a small, well-specified task, checking what it produces, and repeating. The model can write code much faster than you can read it, so the amount you can review, not the amount it can generate, sets the pace at which you can work safely.

If you ask for "CSV export on the reports page" and accept 300 changed lines across six files after a quick skim, you have no way of knowing what else changed. Suppose the change also rewrote a date helper, and invoices showed the wrong month a week later because of it. Nobody had read the whole change, so nobody noticed.

The loop for one change

Size each step to something you can read and test in a few minutes. For CSV export, that means asking first for a function that turns rows into CSV text, together with its tests, then for the button, then for the download. Every step follows the same five parts.

  1. State the goal and attach the files. The model only knows what is in its context, so include the code it will change and the code it has to fit with.
  2. Ask for one small change. That is one function or one fix, and ideally one file.
  3. Read the diff, which is the list of lines added and removed, before you run anything.
  4. Run the tests. If one fails, paste the exact error message and the failing test back to the model, because "it doesn't work" gives it nothing to act on.
  5. Commit. That gives you a safe point to return to if the next step goes wrong.

What to put in the request

A request with no context leaves the model to guess the details, and its guesses will be the common cases rather than the ones your code needs.

Request with no contextIllustrative example. Real replies vary.
You
Write a median function in JavaScript.
Model
function median(arr) { arr.sort((a, b) => a - b); return arr[Math.floor(arr.length / 2)]; }

This looks reasonable, but it has three problems. For an even number of values it returns the upper middle value instead of the average of the two middle values. It sorts the caller's array in place. It returns undefined for an empty list. The model could only have known about the first problem; the other two depend on how your code uses the function.

Request with files, goal and limitsIllustrative example. Real replies vary.
You
Add a median(nums) function to stats.js (below). The reports page uses it to show the typical response time in milliseconds. Requirements: - Even number of values: return the average of the two middle values. - Empty list: throw an error. - Do not change the input array. The caller reuses it to draw a chart. - Match the style of mean() in the same file. - Only change stats.js. Also write tests for each requirement, using node:assert like stats.test.js (below). <file name="stats.js"> [contents] </file> <file name="stats.test.js"> [contents] </file>

This version states the goal, supplies the files, lists the rules that are specific to your code, and says how the result will be checked. A rule such as "do not change the input array" is something only you know, so the model cannot supply it.

Tests as the definition of done

A test turns "this looks right" into "this does what I specified". Either write the tests before the implementation, or read the ones the model wrote with care, because a wrong test makes wrong code look correct. The tracer below runs the five tests from the request above against three successive versions of the function.

Five tests, three versions of medianUse the arrows or ← → keys
  1. tests
    expectedv1v2v3
    [3, 1, 2]2
    [4, 1, 3, 2]2.5
    [7]7
    input unchangedyes
    [] throwsyes
    version
    none yet

    1The five tests that pin down the brief, before any version has been run.

  2. tests
    expectedv1v2v3
    [3, 1, 2]22
    [4, 1, 3, 2]2.53
    [7]77
    input unchangedyesno
    [] throwsyesno
    version
    v1
    passed
    2 / 5

    2v1 is the quick answer from the first prompt. Odd lengths pass. For four values it returns 3, the upper middle, not 2.5.

  3. tests
    expectedv1v2v3
    [3, 1, 2]22
    [4, 1, 3, 2]2.53
    [7]77
    input unchangedyesno
    [] throwsyesno
    version
    v1
    next
    paste errors back

    3arr.sort also sorts the caller's array in place, and an empty list returns undefined. You paste the three failure messages back.

  4. tests
    expectedv1v2v3
    [3, 1, 2]222
    [4, 1, 3, 2]2.532.5
    [7]777
    input unchangedyesnono
    [] throwsyesnoyes
    version
    v2
    passed
    4 / 5

    4v2 adds the empty check and averages the two middles. Four pass. It still sorts the input, so the chart would get a sorted array.

  5. tests
    expectedv1v2v3
    [3, 1, 2]222
    [4, 1, 3, 2]2.532.5
    [7]777
    input unchangedyesnono
    [] throwsyesnoyes
    version
    v2
    next
    sort a copy

    5A quick read misses this bug because every return value is correct. Only the input check catches it, and that check exists because the brief said the caller reuses the array.

  6. tests
    expectedv1v2v3
    [3, 1, 2]2222
    [4, 1, 3, 2]2.532.52.5
    [7]7777
    input unchangedyesnonoyes
    [] throwsyesnoyesyes
    version
    v3
    passed
    5 / 5

    6v3 sorts a copy. All five pass. The final diff touches only stats.js and its test file, so you commit.

1 / 6

The final version and its tests are below. Each requirement from the request has one check.

The final version and its contract
const assert = require("node:assert");
 
function median(nums) {
  if (nums.length === 0) throw new Error("median of empty list");
  const sorted = [...nums].sort((a, b) => a - b); // copy: callers reuse nums
  const mid = Math.floor(sorted.length / 2);
  if (sorted.length % 2 === 1) return sorted[mid];
  return (sorted[mid - 1] + sorted[mid]) / 2;
}
 
assert.strictEqual(median([3, 1, 2]), 2);
assert.strictEqual(median([4, 1, 3, 2]), 2.5);
assert.strictEqual(median([7]), 7);
const times = [120, 80, 95];
median(times);
assert.deepStrictEqual(times, [120, 80, 95]); // input not changed
assert.throws(() => median([]));
def median(nums):
    if not nums:
        raise ValueError("median of empty list")
    ordered = sorted(nums)  # copy: callers reuse nums
    mid = len(ordered) // 2
    if len(ordered) % 2 == 1:
        return ordered[mid]
    return (ordered[mid - 1] + ordered[mid]) / 2
 
assert median([3, 1, 2]) == 2
assert median([4, 1, 3, 2]) == 2.5
assert median([7]) == 7
times = [120, 80, 95]
median(times)
assert times == [120, 80, 95]  # input not changed
try:
    median([])
    raise AssertionError("expected an error")
except ValueError:
    pass

In Python, the equivalent of the in-place bug is calling nums.sort() instead of sorted(nums), and the same test catches it.

Reading the diff

Read every line of the diff, and read it with specific questions in mind.

  • Did it change anything you did not ask for? Renames, reformatting and small improvements in other files are where unwanted behaviour changes hide.
  • Did it touch the tests? A test that was loosened or deleted makes the run green without fixing anything.
  • Did it add a dependency? Check that the package exists and is the one you intended. Models sometimes suggest plausible package names that do not exist, and Privacy and Security explains why attackers register such names.
  • Does it hide errors? An empty catch block, or a default value that swallows bad input, turns a loud failure into a silent one.
  • Can you explain every line? If you cannot, ask the model to explain it, and then check the explanation against the code instead of trusting it.

Choosing how to start a task

Tests first

Ask the model to write the tests and show them to you before it writes any code. You review a short list of expected behaviours, which is much easier than reviewing an implementation, and the tests then judge the code that follows. Use this when the behaviour is clear and can be checked automatically, such as a pure function, a parser or a validation rule. It works poorly for visual layout or anything else that is hard to assert on.

Plan first

For a change that spans several files, ask for a short plan before any code: which files will change, what each change does, and what could break. Correct the plan, and then ask for the steps one at a time. A wrong plan costs you one sentence to fix, while a wrong 300-line change costs you a full review. The risk is accepting a plan that sounds sensible without checking it against the codebase, so name the files and functions the plan refers to and verify they exist.

Exploring and then discarding

When you do not know how something should work, such as an unfamiliar library or an approach you have not tried, it is reasonable to let the model write a quick prototype that you plan to throw away. Keep it on a separate branch and do not merge it. Once you understand the approach, start again with a precise request, because prototype code is rarely written to the standard you would accept in the main codebase.

Pitfalls: large changes, edited tests and long sessions

Assistants that edit files and run commands

Many coding assistants do more than answer in a chat window. They read your repository, edit several files and run commands such as the test suite. This removes the copy and paste, but it does not change the rule that you review what was produced. The assistant can now change many files in one step, so the diff you read is larger and an unrelated change is easier to miss.

Three habits keep this manageable. Work on a branch, so that the whole attempt can be thrown away with one command. Allow the assistant to run commands that only read or test, and approve anything that deletes files, installs packages or touches the network one command at a time. Keep secrets such as API keys out of the files the assistant can read, because their contents become part of its context. Privacy and Security covers what happens to that context.

It also helps to keep a short file of project conventions that the assistant reads at the start of each session, for example how to run the tests, which folders are generated, and which style rules the team uses. This replaces repeating the same rules in every request. Keep it short and correct it when a rule changes, because an outdated rule is followed just as faithfully as a current one.

Try it: Rewrite a coding request

This request produced a function that worked on the example but broke the app in two places. Rewrite it with the goal, the files, the rules and the way the result will be checked.

Show a sample answer

One stronger version:

Rewritten requestIllustrative example. Real replies vary.
You
Add formatPrice(cents) to money.js (below). It is used on the checkout page and in emailed receipts. Rules: - Input is a whole number of cents. 1999 becomes "$19.99", 5 becomes "$0.05", 0 becomes "$0.00". - Negative values are refunds: -250 becomes "-$2.50". - Do not use floating-point division on the cents; build the string from whole numbers. - Only change money.js and money.test.js. First write the tests for each rule above and show them to me. Then write the function. <file name="money.js"> [contents] </file>

This works because it says where the function is used, so the model knows the format matters. The examples double as tests and settle the edge cases of small amounts, zero and refunds. Asking for the tests first lets you check the specification before any code exists.

Check yourself

Quick check

A one-sentence feature request returns a 400-line change across eight files. What is the best next step?

In the tracer, why did v2 pass four tests but still have a bug?

After you report a failing test, the model's next diff changes assert.strictEqual(median([4, 1, 3, 2]), 2.5) to expect 3. What does that tell you?

What to practise next

On your next task, write or read the tests before you look at the implementation, and commit after each step that passes. Then continue with Verifying AI Output, which covers checking facts, numbers and sources as well as code.