Practical rules for writing code that is easy to read, change, and maintain.
Clean code is not about perfection. It is about reducing the cost of change.
Names should reveal intent:
// Bad
const d = 86400000;
// Good
const MILLISECONDS_IN_A_DAY = 86_400_000;
A function should do one thing and do it well. If you need to scroll to understand it, it is probably too long.
Prefer early returns:
function processUser(user?: User) {
if (!user) return;
if (!user.isActive) return;
// main logic here
}
Code should explain what. Comments should explain why.
// Compensate for the timezone offset because the API returns UTC
const localDate = new Date(apiDate.getTime() + offset);
Prefer boring, predictable patterns over clever one-liners that only you understand.
| Principle | Description |
|---|---|
| DRY | Don't Repeat Yourself |
| KISS | Keep It Simple, Stupid |
| YAGNI | You Aren't Gonna Need It |
| Single Responsibility | One reason to change |
Code is read far more often than it is written. Optimize for the reader.