DEV Community

Daniel 489
Daniel 489

Posted on

The Art of Writing Clean Code: Lessons from 10 Years of Mistakes

Let's be real for a second. We've all written code that made us cringe six months later. I've definitely pushed things to production that I'm not proud of. But over the years, I've learned that writing clean code isn't about being a genius it's about being intentional, disciplined, and a little bit humble.

Here are some lessons that stuck with me, with real code examples to drive each point home.

1. Names Matter More Than You Think
Your variable and function names should tell a story. If someone reads your code without comments and can't understand what's happening, you've already lost.

** Bad:**
javascript
function d(x, y) {
  return x * y / 100;
}
** Good:**
javascript
function calculateDiscount(price, discountPercentage) {
  return price * discountPercentage / 100;
}
Enter fullscreen mode Exit fullscreen mode

See the difference? The good version is self-explanatory. No comment needed.

  1. Keep Functions Small and Focused A function should do one thing and do it well. If you're writing a function that's 50 lines long and does three different things, it's time to break it apart.
 Bad:

javascript
function processOrder(order) {
  // calculate total
  let total = 0;
  order.items.forEach(item => total += item.price * item.qty);
  // apply discount
  if (order.coupon) {
    total = total * 0.9;
  }
  // save to database
  db.orders.save(order);
  // send email
  email.send(order);
  return total;
}
 Good:

javascript
function calculateTotal(order) {
  return order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

function applyDiscount(total, coupon) {
  return coupon ? total * 0.9 : total;
}

function processOrder(order) {
  const total = calculateTotal(order);
  const finalTotal = applyDiscount(total, order.coupon);
  // save to database
  // send email
  return finalTotal;
}
Enter fullscreen mode Exit fullscreen mode

Now each function has one responsibility. It's easier to test, debug, and understand.

3. Comments Are Not a Substitute for Clear Code
Comments are great for explaining why something is done a certain way. But if you're using comments to explain what your code does, your code probably needs to be clearer.

** Bad:**

javascript
// loop through users
for (let i = 0; i < users.length; i++) {
  // check if user is active
  if (users[i].status === 'active') {
    // send email
    sendEmail(users[i]);
  }
}
** Good:**

javascript
const activeUsers = users.filter(user => user.status === 'active');
activeUsers.forEach(activeUser => sendEmail(activeUser));
Enter fullscreen mode Exit fullscreen mode

The code speaks for itself. No comments needed.

When comments are actually useful:

javascript

// Users must receive emails before 8am to avoid timezone issues
const activeUsers = users.filter(user => user.status === 'active');
activeUsers.forEach(activeUser => sendEmail(activeUser));
Enter fullscreen mode Exit fullscreen mode

The comment explains why — the what is already clear.

4. Consistency Is Underrated
Pick a style guide and stick to it. Whether it's tabs vs spaces, naming conventions, or file structure — consistency across your codebase makes everything easier.

** Inconsistent:**

javascript
function getUserData(id) {
  let user = db.find('users', id);
  var userData = {
    Name: user.name,
    age: user.age,
  };
  return userData;
}
** Consistent:**

javascript
function getUserData(id) {
  const user = db.find('users', id);
  const userData = {
    name: user.name,
    age: user.age,
  };
  return userData;
}
Enter fullscreen mode Exit fullscreen mode

Use tools like Prettier and ESLint to automate this so you never have to think about it.

5. Test Your Code Like You Mean It
Don't skip tests because you're in a hurry. Tests are your safety net.

Example of a simple unit test:

javascript
// The function we want to test
function calculateDiscount(price, discountPercentage) {
  return price * discountPercentage / 100;
}

// The test
function testCalculateDiscount() {
  const result = calculateDiscount(100, 10);
  const expected = 10;
  if (result === expected) {
    console.log('✅ Test passed');
  } else {
    console.log('❌ Test failed: Expected', expected, 'got', result);
  }
}

testCalculateDiscount();
Enter fullscreen mode Exit fullscreen mode

Even a simple test like this catches mistakes early. Build from there.

6. Avoid Deeply Nested Code
Deeply nested code is hard to read and reason about. Flatten it whenever possible.

 Bad:

javascript
function processPayment(order) {
  if (order.paymentStatus !== 'paid') {
    if (order.total <= 1000) {
      if (order.customer.verified) {
        processTransaction(order);
      } else {
        console.log('Customer not verified');
      }
    } else {
      console.log('Order exceeds limit');
    }
  } else {
    console.log('Already paid');
  }
}
 Good:

javascript
function processPayment(order) {
  if (order.paymentStatus === 'paid') {
    return console.log('Already paid');
  }

  if (order.total > 1000) {
    return console.log('Order exceeds limit');
  }

  if (!order.customer.verified) {
    return console.log('Customer not verified');
  }

  processTransaction(order);
}
Enter fullscreen mode Exit fullscreen mode

See how the good version uses early returns to flatten the flow? Much easier to follow.

7. Use Descriptive Booleans
Boolean variable names should sound like yes/no questions.

 Bad:

javascript
const flag = user.active;
if (flag) {
  // ...
}
 Good:

javascript
const isActive = user.active;
const isEligible = user.age >= 18 && user.status === 'active';
const hasValidEmail = user.email.includes('@');

if (isActive && isEligible && hasValidEmail) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

The code reads like English. It's almost conversational.

8. Clean Up Your Imports
Messy imports make your file look cluttered before you even start reading.

 Bad:

javascript
import React, { useState, useEffect, useRef, useCallback, useMemo, useContext } from 'react';
import axios from 'axios';
import lodash from 'lodash';
import moment from 'moment';
// 20 more imports...
 Good:

javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { formatDate, parseDate } from './utils/dateHelpers';
import { validateEmail, validatePhone } from './utils/validators';
Enter fullscreen mode Exit fullscreen mode

Group and organize your imports logically. It makes the file more approachable.

9. Write Self-Documenting Tests
Your tests should be easy to read and understand, even if someone didn't write them.

 Bad:

javascript
test('user', () => {
  const u = createUser('john', 'j@gmail.com');
  expect(u.age).toBe(30);
});
 Good:

javascript
test('should create a user with the provided name and email', () => {
  const user = createUser('John', 'john@gmail.com');
  expect(user.name).toBe('John');
  expect(user.email).toBe('john@gmail.com');
});
Enter fullscreen mode Exit fullscreen mode

The test description says exactly what it's testing, and the test itself reads clearly.

10. Stay Curious
Technology changes fast. That's not a reason to be overwhelmed — it's a reason to stay curious. Explore new tools, frameworks, and languages. Build side projects. Read others' code.

But remember: the fundamentals never go out of style.

Final Thought
Clean code isn't about perfection. It's about making your code easy to understand, easy to change, and easy to collaborate on. It's about respecting the people who will work with your code — including your future self.

What's the biggest lesson you've learned in your coding journey?

Top comments (0)