What Is Clean Code? 10 Golden Rules for Writing Better Software
Writing "code that works" is easy. Writing "code that's readable, maintainable, and sustainable" is an art. Robert C. Martin's (Uncle Bob) famous book Clean Code is the manifesto of this art.
Definition
Clean code is code that another developer (or yourself 6 months later) can easily read, understand, and modify.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." — Martin Fowler
10 Golden Rules
1. Meaningful Naming
Variable, function, and class names should clearly state what they do:
// ❌ Bad
const d = new Date();
const arr = users.filter(u => u.a > 18);
// ✅ Good
const currentDate = new Date();
const adultUsers = users.filter(user => user.age > 18);
2. Single Responsibility (SRP)
Every function, every class should do one thing:
// ❌ Bad — Multiple responsibilities
function processOrder(order) {
validateOrder(order);
calculateTax(order);
chargeCreditCard(order);
sendEmail(order);
updateInventory(order);
}
// ✅ Good — Each function does one thing
function processOrder(order) {
const validatedOrder = validateOrder(order);
const taxedOrder = applyTax(validatedOrder);
const payment = processPayment(taxedOrder);
notifyCustomer(payment);
updateStock(taxedOrder);
}
3. Small Functions
Functions should not exceed 20 lines. Long functions should be broken into sub-functions.
4. Code Over Comments
Good code explains itself. Comments should explain why, not what:
// ❌ Bad comment
// Check user's age
if (user.age >= 18) { ... }
// ✅ Good — Code is self-explanatory
if (user.isAdult()) { ... }
// ✅ Good comment — Explains the why
// Legal requirement: GDPR requires parental consent
// for users under 18 to create accounts
if (!user.isAdult() && !user.hasParentalConsent()) { ... }
5. DRY (Don't Repeat Yourself)
Never write the same code twice. Extract repeated logic into shared functions.
6. Proper Error Handling
Don't silently swallow errors. Use meaningful error messages:
// ❌ Bad
try { ... } catch(e) { console.log(e); }
// ✅ Good
try {
const user = await findUser(userId);
if (!user) throw new UserNotFoundError(userId);
} catch (error) {
logger.error('User not found', { userId, error });
throw error;
}
7. Consistent Code Style
Use consistent style across the project: indentation, naming conventions, file structure. Automate with ESLint/Prettier.
8. Write Tests
Untested code is unreliable code. Write at least unit tests for every function.
9. Early Returns (Guard Clauses)
Use early returns instead of nested if-else blocks:
// ❌ Bad — Arrow code
function getDiscount(user) {
if (user) {
if (user.isPremium) {
if (user.yearsActive > 2) {
return 0.2;
}
return 0.1;
}
return 0.05;
}
return 0;
}
// ✅ Good — Guard clauses
function getDiscount(user) {
if (!user) return 0;
if (!user.isPremium) return 0.05;
if (user.yearsActive <= 2) return 0.1;
return 0.2;
}
10. Boy Scout Rule
"Leave the campground cleaner than you found it." Make at least one small improvement with every commit.
SOLID Principles
| Principle | Description | |-----------|-------------| | Single Responsibility | One class, one reason to change | | Open/Closed | Open for extension, closed for modification | | Liskov Substitution | Subclasses must be substitutable | | Interface Segregation | Small, focused interfaces | | Dependency Inversion | Depend on abstractions, not concretions |
Conclusion
Writing clean code is a habit. It takes time initially, but compounds exponentially over time. Readable code = fewer bugs, faster development, happier team.
Learn Clean Code and SOLID principles with interactive missions on the Foundation career path at LabLudus.