Track 04 · Lesson 14 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

Least surprise

Lesson 14 of 15· 5 min

Code should do what its name and shape suggest, and nothing more.

Add a tag

This is a real form

This is a real HTML form. Try adding a tag.

q3

The Add tag button has no type attribute. Type a tag and click it.

NewProjectForm.tsxWithout it
export function NewProjectForm() {
  return (
    <form onSubmit={createProject}>
      <Input name="name" />
      <Input value={tag} onChange={(e) => setTag(e.target.value)} />
      {/* No type, so inside a form it defaults to "submit" */}
      <button onClick={addTag}>Add tag</button>
      <button>Create project</button>
    </form>
  );
}

// The same trap in functions: the name promises a read,
// the body quietly writes, tracks and caches.
function getUser(id: string): User {
  const user = db.users.find(id);
  localStorage.setItem("lastUser", JSON.stringify(user));
  analytics.track("user_viewed", { id });
  return user;
}

Names and shapes are promises#

A reader predicts what code does from its name, its signature and how it looks. A function called getUser that also writes to the database, a isValid that throws, a save button that also navigates away: each one breaks that promise, and the bug reports land somewhere far from the cause.

The HTML default in the demo is a famous trap: inside a form, a button with no type is type="submit". The fix is one attribute, type="button", and it's good practice to write it on every button that doesn't submit.

Make surprises impossible, not just documented#

A comment saying "careful, this also submits" helps the person who reads it. Changing the code so it can't surprise anyone helps everyone. Rename the function, split the side effect out, or set the attribute.

Check yourself

Inside a form, what does a <button> with no type attribute do when clicked?