Skip to content

Code Placement ​

Put new code where it belongs, not where it's easiest to type. A file should read as if it had been designed with the new code in mind from the start.

The rule ​

  • A new function goes next to its relatives. Place it with the functions it calls or is called alongside, at the altitude it works at. The bottom of the file is right only when that's where it belongs.
  • A new case goes inside the structure it extends. Add the entry to the table, the branch to the existing dispatch, the field to the existing shape. Don't bolt on a special-case if in front of the structure because that was quicker than fitting it in.
  • When new knowledge changes the design, change the design. If the new case shows the old structure was wrong, restructure (in verified steps, per Refactoring) rather than layering a flag or workaround over it.

❌ DON'T append the new handler at the bottom and special-case it

js
function render(node) {
  if (node.type === "video") return renderVideo(node);
  return RENDERERS[node.type](node);
}

// ...200 lines later, at the end of the file
function renderVideo(node) { /* ... */ }

✅ DO fit it into the structure it extends

js
const RENDERERS = {
  image: renderImage,
  video: renderVideo,
  text: renderText,
};

function renderImage(node) { /* ... */ }

function renderVideo(node) { /* ... */ }

Why ​

A reader who finds related code in one place, in one structure, understands it in one pass; scattered special cases make every reader reconstruct the design the writer skipped. The principle behind this: Optimize for the Reader.