Quick answer: Clean code is code that another developer can read, understand and change safely. The core habits: meaningful names, small functions that do one thing, no duplication, clear error handling, minimal comments that explain why, consistent formatting, and automated tests. Principles such as SOLID, DRY, KISS and YAGNI guide the bigger design decisions.
Code is read far more often than it is written. Messy code slows every future feature, causes bugs and burns out teams. The good news: clean code is a set of learnable habits. Here are the ones that matter most, with before-and-after examples.
1. Names that reveal intent
// β
const d = 86400; function calc(a, b) { ... }
// β
const SECONDS_PER_DAY = 86400; function calculateInvoiceTotal(items, vatRate) { ... }- Use nouns for variables/classes, verbs for functions.
- Avoid abbreviations except universal ones (id, url).
- Booleans read like questions:
isActive,hasPermission.
2. Small functions that do one thing
// β One function validates, saves, emails and logs
// β
Split by responsibility
function registerUser(input) {
const data = validateRegistration(input);
const user = userRepository.create(data);
welcomeMailer.send(user);
return user;
}If you need the word "and" to describe a function, it probably does too much.
3. Avoid deep nesting β use guard clauses
// β
if (user) { if (user.isActive) { if (order.total > 0) { process(order); } } }
// β
if (!user || !user.isActive) return;
if (order.total <= 0) return;
process(order);4. DRY β but not too early
Don't Repeat Yourself: duplicated business rules drift apart and cause bugs. But wait until you see the same logic two or three times before abstracting β the wrong abstraction is worse than duplication.
5. KISS and YAGNI
- Keep It Simple β the simplest solution that works is easiest to maintain.
- You Aren't Gonna Need It β do not build features or configuration "for the future" that nobody asked for.
6. SOLID in one line each
Principle | Meaning |
|---|---|
S β Single Responsibility | A class should have one reason to change |
O β Open/Closed | Extend behaviour without modifying stable code |
L β Liskov Substitution | Subtypes must work wherever the base type works |
I β Interface Segregation | Many small interfaces beat one giant one |
D β Dependency Inversion | Depend on abstractions; inject dependencies |
7. Remove magic numbers and strings
// β if (status === 3) ...
// β
if (status === OrderStatus.Shipped) ...8. Handle errors deliberately
- Never swallow exceptions silently (
catch {}). - Fail fast with clear messages at the boundary (validation).
- Use domain-specific exceptions:
InsufficientBalanceError. - Log with context (IDs), never with passwords or personal data.
9. Comments: explain why, not what
// β increment i by 1
i++;
// β
ZATCA requires the counter to never reset, even after a failed submission
invoiceCounter++;If you need a comment to explain what the code does, try renaming or extracting a function first.
10. Consistent formatting β automated
Use formatters and linters (Prettier, ESLint, PHP-CS-Fixer/Pint, dotnet format, Black/Ruff) in pre-commit hooks and CI. Debates about style end when a tool decides.
11. Tests as a safety net
- Write unit tests for business rules and integration tests for important flows.
- Test names describe behaviour:
applies_vat_to_taxable_items_only. - Arrange β Act β Assert structure.
- Tests let you refactor without fear.
12. The Boy Scout Rule
"Leave the code a little cleaner than you found it." Rename a confusing variable, extract a function, delete dead code β in small steps with every change.
Code review checklist
- Can I understand this without asking the author?
- Are names clear and functions small?
- Is there duplicated business logic?
- Are errors and edge cases handled?
- Are there tests for the new behaviour?
- Is anything unnecessary (YAGNI)?
Summary
- Readable names, small focused functions, guard clauses.
- DRY, KISS, YAGNI and SOLID guide design.
- No magic values, no silent errors.
- Comments explain why; tools enforce formatting; tests protect changes.