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 most important principles with practical examples.

This article complements clean-code-solid-prinzipien.mdx.

In a Nutshell

Clean Code means writing code that other developers can quickly understand, modify, and extend. Core principles: meaningful names, small functions, DRY, KISS, YAGNI.

Compact Technical Definition

Clean Code is an approach to software development that prioritizes readability, maintainability, and extensibility. Shaped by Robert C. Martin, it encompasses principles like expressive 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: overly 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)

Implement only what’s needed 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: errors swallowed
function getData() {
  try { return fetchFromAPI(); }
  catch (e) { return null; }
}

// Good: errors logged and propagated
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 linesSplit responsibilities
Duplicate CodeSame logic multiple timesExtract common code
Long Parameter List> 4 parametersUse parameter object
Deep Nesting> 3 levelsEarly return / guard clauses
Dead CodeUnused codeDelete it
Magic NumbersUnnamed constantsUse 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 primary documentation
  • Functions: single responsibility, maximum 20–30 lines
  • Boy Scout Rule: leave code cleaner than you found it
  • Command-Query Separation
  • Recognize 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. Simplicity over complexity.

3. What does YAGNI mean?

You Aren’t Gonna Need It. Implement only what’s needed right now.

4. How long should a function be?

Maximum 20–30 lines, with a single responsibility.

5. What is the Boy Scout Rule?

Leave 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 an underlying problem, such as long methods or duplication.

9. Who pioneered Clean Code?

Robert C. Martin (Uncle Bob).

10. What is deep nesting?

More than 3 levels of nesting. Fix it with early return 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 never executes. Delete it.

13. What is a long parameter list?

More than 4 parameters. Use a parameter object instead.

14. What is refactoring?

Improving code structure without changing its behavior. A continuous process.

15. Why is Clean Code important?

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

If you have further questions, see 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.

Sources

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

Book Recommendations on Software Quality

To deepen your knowledge of 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:

Nächster Artikel in Software Quality

Weiterlesen
Code Coverage & Testing Metrics: Strategies

Related Posts