Skip to main content

Command Palette

Search for a command to run...

How to Write Clean Code That You Won’t Hate Later

Updated
4 min read

Have you ever looked at your old code and wondered, "Who wrote this mess?"—only to realize it was you? Writing clean, maintainable code isn’t just about making things look pretty; it’s about ensuring that future-you (or your teammates) can understand and modify the code without frustration.

Here’s how to write clean code that you won’t regret later:

---

1. Use Meaningful Names

Bad variable names lead to confusion. Always choose names that describe what the variable, function, or class does.

❌ Bad:

```

let d = new Date();

let x = 50;

```

✅ Good:

```

let currentDate = new Date();

let maxRetryAttempts = 50;

```

Tip: Avoid single-letter variables (except in loops) and use consistent naming conventions (camelCase for JavaScript, snake_case for Python, etc.).

---

2. Keep Functions Small and Focused

Each function should do one thing and do it well. If it’s trying to do too much, break it into smaller functions.

❌ Bad (Too much happening):

```

function processOrder(order) {

validateOrder(order);

saveToDatabase(order);

sendEmailConfirmation(order);

}

```

✅ Good (Single Responsibility Principle):

```

function validateOrder(order) { /* validation logic */ }

function saveOrder(order) { /* save logic */ }

function sendConfirmation(order) { /* email logic */ }

```

Tip: If you can’t describe what a function does in one sentence, it’s probably doing too much.

---

3. Avoid Magic Numbers and Hardcoded Values

Magic numbers make your code unreadable and difficult to update.

❌ Bad:

```

if (user.age > 18) {

console.log("Access granted");

}

```

✅ Good:

```

const min_age = 18;

if (user.age > min_age) {

console.log("Access granted");

}

```

Tip: Use constants for values that might change, and give them meaningful names.

---

4. Write Comments Wisely

Bad comments can be worse than no comments at all. Your code should be self-explanatory, and comments should explain why, not what.

❌ Bad Comment (Redundant):

```

// Increment x by 1

x = x + 1;

```

✅ Good Comment (Explains Why):

```

// Adding 1 because arrays are 0-indexed

let position = userInput + 1;

```

Tip: If you feel the need to explain what the code does, consider rewriting it to make it clearer instead.

---

5.Keep Your Code DRY (Don’t Repeat Yourself)

Duplicated code makes debugging a nightmare. If you find yourself copying and pasting, it’s time to refactor.

❌ Bad (Repetitive Code):

```

function getAdminEmail() {

return "admin@example.com";

}

function getSupportEmail() {

return "support@example.com";

}

```

✅ Good (Reusable Code):

```

function getEmail(type) {

const emails = {

admin: "admin@example.com",

support: "support@example.com",

};

return emails[type];

}

```

Tip: Use functions, loops, and configuration objects to avoid duplication.

---

6. Handle Errors Gracefully

Always expect things to go wrong and handle errors properly.

❌ Bad:

```

const data = fetchUserData();

console.log(data.name); // Crashes if data is null

```

✅ Good:

```

try {

const data = fetchUserData();

console.log(data?.name || "No name available");

} catch (error) {

console.error("Failed to fetch user data", error);

}

```

Tip: Use `try...catch` for async operations and null checks (`?.` and `||`) to prevent crashes.

---

7. Stick to a Consistent Code Style

Mixing different styles makes the code harder to read. Use tools like Prettier and ESLint to enforce a consistent format.

Example: Linting Rules in `.eslintrc.js`

```

module.exports = {

rules: {

"indent": ["error", 2],

"quotes": ["error", "double"],

"semi": ["error", "always"]

}

};

```

Tip: Follow industry standards for formatting and use linters to catch inconsistencies automatically.

---

8. Write Tests for Your Code

Testing ensures that your code works as expected and prevents future issues.

Example: Simple Jest Test

```

function add(a, b) {

return a + b;

}

test("adds 2 + 3 to equal 5", () => {

expect(add(2, 3)).toBe(5);

});

```

Tip: Even basic tests save time debugging in the long run.

---

Final Thoughts

Writing clean code isn’t about perfection—it’s about making your code readable, maintainable, and efficient. Future-you will thank you!

Here’s a quick recap:

✅ Use meaningful variable names

✅ Keep functions small and focused

✅ Avoid magic numbers and hardcoded values

✅ Write useful comments (but not too many)

✅ Follow the DRY principle

✅ Handle errors properly

✅ Stick to a consistent style

✅ Write tests to ensure your code works

What’s your favorite clean code principle? Let me know in the comments! 🚀