Clean Code Principles
Clean Code isn’t an end in itself—it’s the foundation for software that can be maintained and extended over years. This article covers the key principles with practical examples.
This article complements clean-code-solid-prinzipien.mdx.
In a Nutshell
Clean Code means writing code so that other developers can quickly understand, modify, and extend it. Core principles: meaningful names, small functions, DRY, KISS, YAGNI.
Technical Definition
Clean Code is an approach to software development that prioritizes readability, maintainability, and extensibility. Popularized by Robert C. Martin, Clean Code encompasses principles like meaningful naming, short functions with a single responsibility, avoiding duplication, simplicity, and consistent refactoring.
Key Principles
1. Meaningful Names
// Bad
const d = 2;
const arr = getUsers();
// Good
const DAYS_IN_WEEK = 7;
const activeUsers = users.filter(u => u.isActive);
2. Small Functions
Functions should be small and do exactly one thing.
// Bad: does too much
function processUser(user) {
user.email = user.email.toLowerCase();
user.name = user.name.trim();
saveToDatabase(user);
sendWelcomeEmail(user);
}
// Good: separated concerns
function normalizeUser(user) {
return { ...user, email: user.email.toLowerCase(), name: user.name.trim() };
}
async function registerUser(user) {
const normalized = normalizeUser(user);
await saveToDatabase(normalized);
await sendWelcomeEmail(normalized);
}
3. DRY (Don’t Repeat Yourself)
// Bad: VAT duplicated
function calculateTotal(items) {
return items.reduce((s, i) => s + i.price * i.qty * 1.19, 0);
}
// Good: centralized constant
const VAT_RATE = 1.19;
function calculateTotal(items) {
return items.reduce((s, i) => s + i.price * i.qty * VAT_RATE, 0);
}
4. KISS (Keep It Simple)
// Bad: unnecessarily abstract
class UserProcessor {
constructor(strategy) { this.strategy = strategy; }
process(user) { return this.strategy.execute(user); }
}
// Good: straightforward
function normalizeEmail(user) {
return { ...user, email: user.email.toLowerCase() };
}
5. YAGNI (You Aren’t Gonna Need It)
Only implement what you need right now.
Additional Principles
Boy Scout Rule
Leave the code cleaner than you found it.
Command-Query Separation
A function should either do something (Command) or return something (Query), not both.
Error Handling
// Bad: error swallowed
function getData() {
try { return fetchFromAPI(); }
catch (e) { return null; }
}
// Good: error logged and re-raised
async function getData() {
try { return await fetchFromAPI(); }
catch (error) {
logger.error('API fetch failed', error);
throw new Error('Failed to load data');
}
}
Clean Code - Refactoring, Patterns, Testen und Techniken für sauberen Code: Deutsche Ausgabe
39,99 €
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
Clean Code für Dummies: Besser programmieren. Professionelle Softwareentwicklung.
24,99 €
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
Besser coden: Best Practices für Clean Code. Das ideale Buch für die professionelle Softwareentwicklung
34,99 €
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
Code Smells
| Smell | Description | Fix |
|---|---|---|
| Long Method | Function > 30 lines | Split it up |
| Large Class | Class > 200 lines | Separate responsibilities |
| Duplicate Code | Same logic repeated | Extract it |
| Long Parameter List | > 4 parameters | Use parameter object |
| Deep Nesting | > 3 levels | Early return / guard clauses |
| Dead Code | Unused code | Delete it |
| Magic Numbers | Unnamed constants | Named constants |
Practical Example: Refactoring
// Before: unreadable, does too much
function calc(o, c, d) {
let r = 0;
for (let i = 0; i < o.length; i++) {
if (o[i].t == 'premium') r += o[i].p * 0.8;
else if (o[i].t == 'vip') r += o[i].p * 0.7;
else r += o[i].p;
}
if (d) r = r * 0.9;
return r * 1.19;
}
// After: Clean Code
const VAT_RATE = 1.19;
const DISCOUNT_MAP = { premium: 0.8, vip: 0.7, standard: 1.0 };
function applyDiscount(price, customerType) {
const factor = DISCOUNT_MAP[customerType] ?? 1.0;
return price * factor;
}
function calculateOrderTotal(orders, hasCoupon = false) {
const subtotal = orders.reduce(
(sum, order) => sum + applyDiscount(order.price, order.type), 0
);
const afterCoupon = hasCoupon ? subtotal * 0.9 : subtotal;
return afterCoupon * VAT_RATE;
}
Key Takeaways
- DRY, KISS, YAGNI as core principles
- Meaningful naming as the most important documentation
- Functions: single responsibility, max 20-30 lines
- Boy Scout Rule: leave code cleaner than you found it
- Command-Query Separation
- Identify and fix Code Smells
- Refactoring as a continuous process
FAQ
1. What does DRY mean?
2. What does KISS mean?
3. What does YAGNI mean?
4. How long should a function be?
5. What is the Boy Scout Rule?
6. What is Command-Query Separation?
7. What are Magic Numbers?
8. What is a Code Smell?
9. Who popularized Clean Code?
10. What is Deep Nesting?
11. Should you use comments?
12. What is Dead Code?
13. What is Long Parameter List?
14. What is Refactoring?
15. Why is Clean Code important?
If you have further questions, check out clean-code-solid-prinzipien.mdx.
Next in the Software Quality Learning Path
The next article in the Software Quality Learning Path covers SOLID Principles Fundamentals — the five principles of object-oriented design: SRP, OCP, LSP, ISP, and DIP.
References
- https://www.oreilly.com/library/view/clean-code/9780134661742/
- https://clean-code-developer.com/
- https://refactoring.com/
Recommended Books on Software Quality
If you want to dive deeper into Clean Code, software quality, and refactoring, we recommend these books:
Software Engineering
Books about software quality, clean code, code reviews and software development processes
Clean Code: A Handbook of Agile Software Craftsmanship von Robert C. Martin
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.
The Pragmatic Programmer: Your Journey to Mastery von David Thomas, Andrew Hunt
Bei Amazon ansehenAffiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.







