Skip to content
IRC-CodingIRC-Coding
Clean CodeDRYKISSYAGNINamingRefactoringSoftware Quality

Clean Code Principles: Readable, Maintainable Code

Master clean code principles: meaningful names, small functions, DRY, KISS, YAGNI with JavaScript and TypeScript examples.

S

schutzgeist

4 min read
Clean Code Principles: Readable, Maintainable Code

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

Clean Code - Refactoring, Patterns, Testen und Techniken für sauberen Code: Deutsche Ausgabe

39,99 €

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Clean Code für Dummies: Besser programmieren. Professionelle Softwareentwicklung.

Clean Code für Dummies: Besser programmieren. Professionelle Softwareentwicklung.

24,99 €

Bei Amazon ansehen

Affiliate-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

Besser coden: Best Practices für Clean Code. Das ideale Buch für die professionelle Softwareentwicklung

34,99 €

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Code Smells

SmellDescriptionFix
Long MethodFunction > 30 linesSplit it up
Large ClassClass > 200 linesSeparate responsibilities
Duplicate CodeSame logic repeatedExtract it
Long Parameter List> 4 parametersUse parameter object
Deep Nesting> 3 levelsEarly return / guard clauses
Dead CodeUnused codeDelete it
Magic NumbersUnnamed constantsNamed 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?

Don’t Repeat Yourself. Every piece of logic should exist in exactly one place.

2. What does KISS mean?

Keep It Simple. Favor simplicity over complexity.

3. What does YAGNI mean?

You Aren’t Gonna Need It. Only implement what you need now.

4. How long should a function be?

Maximum 20-30 lines, with a single responsibility.

5. What is the Boy Scout Rule?

Leave the code cleaner than you found it.

6. What is Command-Query Separation?

A function either does something or returns something, not both.

7. What are Magic Numbers?

Unnamed numbers in code. Replace them with named constants.

8. What is a Code Smell?

An indicator of a deeper problem, such as Long Method or code duplication.

9. Who popularized Clean Code?

Robert C. Martin (Uncle Bob).

10. What is Deep Nesting?

More than 3 levels of nesting. Solution: use early returns or guard clauses.

11. Should you use comments?

Good comments explain WHY, not WHAT. Code should be self-explanatory.

12. What is Dead Code?

Code that is never executed. Delete it.

13. What is Long Parameter List?

More than 4 parameters. Solution: use a parameter object.

14. What is Refactoring?

Improving code structure without changing behavior. An ongoing process.

15. Why is Clean Code important?

Code is read far more often than it is written. Clean Code reduces maintenance costs and errors.

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

  1. https://www.oreilly.com/library/view/clean-code/9780134661742/
  2. https://clean-code-developer.com/
  3. https://refactoring.com/

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

Clean Code: A Handbook of Agile Software Craftsmanship von Robert C. Martin

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

The Pragmatic Programmer: Your Journey to Mastery von David Thomas, Andrew Hunt

The Pragmatic Programmer: Your Journey to Mastery von David Thomas, Andrew Hunt

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts