Track 04 · Lesson 14 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
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.
The Add tag button has no type attribute. Type a tag and click 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