Clean code essentials: names, functions and simplicity
The small daily habits that make code easy to read, review and change.
Key takeaways
- Code is read far more often than it is written, so optimize for the reader.
- Good names and small functions beat clever code and comments.
- Simple and easy are different. Prefer simple.
Clean code isn't about style rules. It's about respect for the next reader, who is often you, six months later, during an incident.
#1. Names that explain themselves
| Unclear | Clear |
|---|---|
d | daysSinceLastLogin |
handle() | retryFailedPayment() |
data2 | activeCustomers |
isValid (of what?) | hasValidShippingAddress |
Name things for what they mean, not how they're implemented. If naming is hard, the design is often unclear.
#2. Small functions that do one thing
A function should fit on a screen and do one thing at one level of abstraction:
async function placeOrder(cart: Cart, user: User) {
validateCart(cart);
const payment = await chargeCustomer(user, cart.total);
const order = await saveOrder(cart, user, payment);
await notifyCustomer(user, order);
return order;
}
You can read it like a story. The details live in well-named helpers.
#3. Flatten the nesting
Use guard clauses to exit early instead of building pyramids of if statements:
function discount(user?: User) {
if (!user) return 0;
if (!user.isMember) return 0;
if (user.years > 5) return 0.15;
return 0.05;
}
#4. Comments explain why, not what
The code says what it does. Comments are for the non-obvious why: business rules, workarounds and links to tickets. If you need a comment to explain what, rename or extract a function instead.
#5. Simple over clever
Rich Hickey's distinction: easy means familiar and close at hand; simple means not intertwined. A clever one-liner may be easy to write but hard to change. Prefer boring, obvious code.
#6. Leave it better (the Boy Scout Rule)
Every time you touch a file, improve one small thing: a name, an extracted function, a deleted dead branch. Small continuous refactoring prevents big painful rewrites.
#7. Consistency beats preference
Follow the conventions already in the codebase. Automate formatting and linting so reviews can focus on design instead of spacing.
AI tip: Give your AI assistant your style guide and a good example file as context. Generated code then matches your conventions and is much easier to review.
Keep reading
Five principles for code that is easy to change, each explained with a short example and a warning about overuse.
How many tests of which kind, how to write tests that catch real bugs, and how AI changes testing.
How to make code reviews fast, kind and genuinely useful, including reviews of AI-generated code.