Clean code basics
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." — Martin Fowler
Code is read far more often than it's written: by your teammates, by reviewers, and by you in six months, when you've forgotten everything. Clean code is easy to read, easy to change and hard to break.
1. Meaningful names
// ✗ What does this do?
function calc(a, b) { return a * b * 0.18; }
let d = 7;
// ✓ Names explain intent
function calculateTax(price, quantity) { return price * quantity * TAX_RATE; }
let daysUntilDeadline = 7;- Variables are nouns:
userCount,selectedProduct. - Booleans read as questions:
isLoggedIn,hasPaid,canEdit. - Functions are verbs:
sendEmail,validatePassword,getUserById. - Avoid abbreviations and single letters (except
iin a short loop). - Use the same word for the same concept everywhere: don't mix
fetch,getandretrieve.
2. Replace magic numbers with named constants
3. Small functions that do one thing
If a function is long, has many levels of nesting, or needs "and" to describe it, split it.
4. Avoid deep nesting with early returns
5. Don't repeat yourself (DRY)
But don't over-abstract: duplication is cheaper than the wrong abstraction. A common rule of thumb is "three strikes, then refactor".
6. Comments: explain why, not what
# ✗ Noise: the code already says this
i = i + 1 # add one to i
# ✓ Explains a non-obvious reason
# The payment provider rejects amounts with more than 2 decimals.
amount = round(amount, 2)If you need a comment to explain what the code does, try renaming or splitting it first. Good code mostly explains itself.
7. Consistent formatting: let tools do it
Don't argue about spaces or tabs. Use an auto-formatter and a linter:
| Language | Formatter | Linter |
|---|---|---|
| JavaScript / TypeScript | Prettier | ESLint |
| Python | Black or Ruff | Ruff, Pylint |
| Go | gofmt (built in) | go vet |
| Rust | rustfmt | Clippy |
Configure your editor to format on save.
8. Handle errors deliberately
Don't silently swallow errors:
// ✗ Hides problems forever
try { saveOrder(order); } catch (e) {}
// ✓ Log it with context, then handle it or re-throw
try {
saveOrder(order);
} catch (err) {
logger.error('Failed to save order', { orderId: order.id, err });
throw err;
}9. Write tests
A test is code that checks your code. Tests let you change code with confidence:
Practice: refactor this
This code works, but it's hard to read. Rename things, extract a function, replace magic numbers and flatten the nesting, without changing what it prints.
1.Which is the best name for a boolean that tracks whether an order is paid?
2.What should code comments mainly explain?