Before You Copy Code
A snippet from documentation, a search result or an assistant is a proposal, not a solution. Before it goes in: what does it do, why does it work, what does it assume, and how does it fail? Four questions that take minutes and are the difference between using a tool and being used by it.
The situation, the reflex, and why it stalls
Every lesson starts where being stuck starts: someone has a problem, and the first move that comes to mind feels like progress.
You have found code that appears to do what you need — in the docs, a forum, or an AI answer. What do you establish before pasting it into the store?
You need to handle the provider's webhook that says a payment succeeded. The provider's docs have a snippet; a forum answer has a longer one that "handles retries"; the assistant produced a third with signature verification. All three look plausible and you do not fully follow any of them.
Paste the most complete-looking one and adjust until it runs. It feels efficient — the problem is solved, the code exists, and writing it from scratch would mean learning the webhook protocol first.
The snippet runs, and the store now contains code nobody on the team can explain. When it fails — a duplicate webhook, a signature mismatch after a key rotation — the debugging starts from zero, in code that was never understood, under pressure.
- The snippet runs, and the store now contains code nobody on the team can explain. When it fails — a duplicate webhook, a signature mismatch after a key rotation — the debugging starts from zero, in code that was never understood, under pressure.
- The snippet's assumptions are inherited silently. The docs example assumes one webhook per payment; the forum answer assumes the webhook arrives after the request returns; the assistant's version assumes a header the provider renamed. Each assumption is true somewhere and one of them is false here.
- The failure modes are unknown. What the snippet does when the webhook is a replay, arrives out of order, or is for a payment the store has not recorded yet is not written in the snippet and was not asked.
- "Don't reinvent the wheel" is the slogan; made precise it says do not re-implement a well-specified, well-tested thing — and it says nothing about pasting an unread example of one. Understanding the wheel is not reinventing it.
The move
Precisely enough to apply it to a problem you have never seen — not a slogan.
- Treat the snippet as a hypothesis about how to solve the problem, and ask four questions before it is accepted. What does it do — line by line, in your own words? Why does it work — what property of the protocol or library makes each step correct? What does it assume — about ordering, uniqueness, headers, versions, the environment? How does it fail — what input or timing makes it wrong, and what happens then?
- If any of the four cannot be answered, the snippet is not ready to go in. The answer may come from the documentation, from a small experiment, from the assistant asked a narrower question — the tools are fine; what is not fine is skipping the answer (Understanding Is Not Delegable).
- Then decide: use as is, adapt, or write your own. Use when the four answers match your case; adapt when one assumption differs and you can name the change; write your own when the snippet solves a neighbouring problem and adapting it would leave its assumptions in place.
- Whatever goes in, the four answers go in with it, as a comment or a test. The test for "how does it fail" is the most valuable artefact the snippet produces, and the snippet never came with it.
Use, adapt, or write
The decision follows from the four answers, and none of the options is the default. The criteria are how well the assumptions match, how well specified the thing is, and whether an adaptation would leave the snippet's assumptions hidden in code that no longer looks like the snippet.
Given what it does, why it works, what it assumes and how it fails — what goes into the store?
when All four answers match your case; the piece is well specified and the snippet is the official form of it — a signature check, a checksum, a protocol handshake.
cost You still owe the tests for its failure modes; the snippet did not come with them.
when One or two assumptions differ and you can name the change — a header name, a raw-body requirement, an idempotency record — without changing why it works.
cost The code drifts from the documented form; the adaptation must be commented so the correspondence survives the next docs update.
when The snippet solves a neighbouring problem — one webhook per payment when yours has several — and adapting would keep its structure while breaking its reasons.
cost You re-derive the parts that were well specified, and can get them wrong; use the snippet as the reference for those parts even while writing the rest.
when A question cannot be answered — the snippet does something you cannot explain and the docs do not help.
cost The problem is still open; the next move is a narrower question to the docs or the assistant, or a small experiment (The Smallest Experiment With a New Technology).
How copied webhook handlers fail
The failures below are the answers to "how does it fail?" for the three snippets. Each was findable by reading and checking; none was findable by running the snippet against a single successful test event, which is the only test a pasted snippet usually gets.
| Trigger | Symptom | Cause | Response |
|---|---|---|---|
| Anyone POSTs to the webhook URL | An order marked paid with no charge | The docs snippet trusts the body; no signature check | Verify the signature over the raw body with the shared secret (Webhook Signature Verification). |
| The provider retries a delivered event | Duplicate side effects — a second confirmation email, double-counted revenue | No record of processed event ids | Store the event id; ignore repeats (Webhook Idempotency). |
| The webhook arrives before our pay request returns | Event dropped as "unknown payment"; order stays unpaid | The snippet assumes the payment row exists | Store the event and reconcile, or look up by the provider's id and create the row. |
| The framework parses JSON before the handler | Every signature fails after deploy | Signature computed over a re-serialised body, not the raw bytes | Capture the raw body at the boundary; the assistant's snippet assumed it was available. |
| The provider renames a header or rotates the secret | All webhooks rejected | Header name and secret hard-coded from a snippet written against an older version | Read the current docs; pin and record the version the handler was written against. |
The snippet, annotated with its answers
What goes into the store is the snippet with the four answers attached where they apply. The comments are not decoration; they are the record that the code was understood, and the test names are the failure modes.
1// Adapted from the provider's example (docs vX). Changes: header name,2// raw body, idempotency, missing-row case — each is a test below.3export async function providerWebhook(rawBody: Buffer, headers: Headers) {4 // WHY: anyone can POST here; the signature proves the provider sent it.5 // ASSUMES: signature is over the raw bytes — parse only after this.6 verifySignature(rawBody, headers.get('provider-signature'), SECRET)7 8 const event = JSON.parse(rawBody.toString())9 10 // FAILS WITHOUT: retries would mark paid twice and email twice.11 if (await events.seen(event.id)) return12 await events.record(event.id)13 14 if (event.type === 'payment.succeeded') {15 // FAILS WITHOUT: the webhook can beat our own request; the row may not exist yet.16 const order = await orders.byProviderPaymentId(event.data.id)17 if (!order) { await pending.store(event); return }18 await orders.markPaid(order.id, event.data.id)19 }20}21 22// tests: replayed event is a no-op; event before order is stored and reconciled;23// bad signature is rejected; unknown event type is ignored and loggedEvery comment answers one of the four questions for a specific line. Someone debugging this at 2 a.m. can see what each step is for, which assumption it rests on, and which test would have caught its failure.
How to do it
Most important first.
- Read it once for what it does, and write a one-line summary per block in your own words. If a block cannot be summarised, that is the block to look up (Reading Documentation With a Goal).
- For each step, name the reason it is correct: "verifies the signature because the provider signs with our secret and anyone can POST to this URL". A step without a reason is a step you cannot defend or modify.
- List the assumptions as sentences and check each against your case: the header names, the event types, the ordering guarantee, the version of the SDK, the presence of the payment row.
- Construct three inputs that would break it — a replay, an out-of-order event, an unknown event type — and say what it does with each. Turn at least one into a test (Counterexample Thinking).
- Decide use / adapt / write, and record why in the commit. If the assistant was involved, ask it the four questions and check its answers against the docs rather than accepting them (AI as Reviewer).
Worked on a concrete problem
The move has to produce something. This is what it produced.
- The docs snippet. Does: parses the body, reads the event type, marks the order paid. Why it works: the provider sends
payment.succeededwith the payment id. Assumes: the body is trustworthy, the payment row exists, each event arrives once. Fails: anyone can POST to the URL; a replayed event marks paid twice; an event for a payment the store has not yet recorded (webhook faster than our request) finds no row and drops it. Three failures found in minutes, none of them in the snippet. - The assistant's version with signature verification. Does: checks a signature header against the body using our secret, then as above. Why: the provider signs with a shared secret, so a valid signature proves origin. Assumes: the header name is
X-Signature, the raw body is available unparsed, timestamps are within a tolerance. Fails: the provider's current docs name the header differently; the framework parses JSON before the handler sees the raw body, so the signature never matches. Two assumptions false for this store — found by checking against the docs, not by running it and seeing. - The decision: adapt. Keep the signature check with the corrected header and raw-body access; add idempotency by recording the event id and ignoring repeats; handle the missing-row case by storing the event and reconciling. Each of those was a failure the four questions found, and each became a test. The webhook handler is now the best-understood code in the store because it was the most questioned (Webhook Idempotency).
How you know it worked
What now exists that did not before, and what question you can now ask.
- You can explain every line of the pasted code to a colleague without reading it, and say why each step is correct.
- The assumptions are written down and each was checked against this system.
- At least one failure mode became a test before the code was merged.
- You chose use, adapt or write for a reason you can state, and the reason is in the commit.
The questions you can now ask
The field this whole domain exists for. After this lesson, these are the questions to put to an unfamiliar problem.
- ?What does this code do, in my own words, block by block?
- ?Why does each step work — what property of the library or protocol makes it correct?
- ?What does it assume about ordering, uniqueness, headers, versions and the state of my system — and which of those is false here?
- ?What input or timing makes it fail, what happens then, and which of those should be a test?
- ?Given the answers, should I use it, adapt it, or write my own — and can I say why?
What can go wrong
- Four questions asked of a three-line helper. The move scales with what the snippet touches: a formatting function needs a glance; a webhook handler that marks orders paid needs all four, in writing.
- Answering the questions from the snippet's own comments. "Handles retries safely" is a claim by the snippet's author about their system; the answer comes from your protocol and your case.
- Refusing all snippets and writing everything from scratch, which re-derives the provider's signature scheme from first principles and gets it subtly wrong. The docs snippet is the right starting point; the questions are how it becomes yours.
- Asking the assistant the four questions and accepting its answers as the check. Its answers are more hypotheses; the documentation and an experiment are the check.
- The four questions cost minutes to an hour per snippet, and on a snippet that turns out to be exactly right that time bought only confidence.
- Adapting a snippet can drift it away from the documented form, so that when the provider updates their docs the correspondence is harder to see; keep the adaptation small and commented.
- Writing your own for something well specified — signature verification — is where "don't reinvent the wheel" is actually right; the questions may tell you to adapt when pride says to write.
- "So never copy code." Copy it; the docs example is usually the best starting point there is. The lesson is about what has to be true before copied code is yours — not about whether to copy.
- "The assistant's version had verification, so it was the best." It had the most features and the most false assumptions. Completeness is not correctness; the four questions distinguish them.
- "Once it has tests, it is understood." The tests are the record of understanding, not a substitute. Tests copied along with the snippet test the snippet's assumptions, not yours.
Where this applies
Problem-solving advice is stated as universal far more often than it is. These labels say what each method is specific to — and where CONTESTED appears, the note gives the strongest form of the opposing view.
- GENERALThe four questions apply to a snippet from any source — docs, forum, assistant, a colleague's old branch — and to any language; what changes is how much each question costs to answer.
- CONTESTEDA serious counter-view: for well-trodden integrations, the vendor's example is more likely to be correct than anything you write after an hour of questioning, and the questioning itself introduces risk by tempting you to adapt what should be used verbatim. On that view the right move is to copy the official example exactly, pin the SDK version, and put your understanding into tests around it rather than into modifications of it. This lesson agrees about verbatim use for well-specified pieces and disagrees that the questions can be skipped: the docs example above assumed the payment row exists, and that assumption was false for this store regardless of how official the snippet was.
- ILLUSTRATIVEThe three snippets, the renamed header and the raw-body parsing problem are invented to show the questions finding failures; no real provider's documentation is quoted.
Where the depth lives
This domain asks the question and hands the answer off by name.
- — The manifesto's delegation cards at /manifesto/delegating are the general form of this lesson: for every tool, what it handles and what stays yours. A pasted snippet is a delegation you did not sign.
- — The manifesto's "review the LLM's answer" at /manifesto/review is the four questions applied when the snippet came from an assistant.