DEV Community

Cover image for How to Write Clean Code – Tips for Developers with Examples
Programming with Shahan
Programming with Shahan

Posted on • Originally published at freecodecamp.org

How to Write Clean Code – Tips for Developers with Examples

Imagine a room so messy you can’t find your keys. Clothes everywhere, books piled up, and chaos reigning supreme.

messy room gif image

Now imagine working in messy code.

It’s the SAME disaster, except now it’s your brain that’s LOSING its sanity.

Image of clean code uncle bob quote
Clean code, on the other hand, is like walking into a spotless room. Everything is exactly where it should be. No stress. No confusion. Just clarity.

Here’s the truth: writing clean code is NOT optional if you want to succeed in software development.

You can write messy code and be the person who struggles to fix every bug, or you can master clean code and DOMINATE every project you touch.


Clean Coder vs. Messy Coder

Let me paint you a picture.

Here’s a graph that shows the journey of two types of coders:

Image of clean code vs bad code graph chart

  • ⚠️ Bad Coder (Red line): Starts fast but crashes hard. The more lines they write, the more trouble they make.
  • ⚡ Clean Code (Blue line): Starts slow but stays consistent. Growth doesn’t stop—it accelerates.

Now, you decide which line you want to follow.

Cost of Bad Code

Image of messy code graph by shahan

To demonstrate this chart, in the initial development phase, bad code is slightly more costly to change than clean code.

However, as we move to the maintenance and refactoring phases, the gap widens SIGNIFICANTLY, with bad code costing nearly TWICE as much as clean code.

By the legacy phase, bad code reaches 100% cost, now its EXTREMELY expensive to update, while clean code remains more manageable at 45%.

No doubt, bad code is a COSTLY problem in software development.


10 Bulletproof Rules for Writing Clean Code

1. Use Names That Mean Something

Naming your variables or functions b or x is a crime. Call them what they are.

// Weak and vague
let b = 5;

// Strong and clear
let numberOfUsers = 5;
Enter fullscreen mode Exit fullscreen mode

People who write unclear names don’t want to own their mistakes. Don’t be that person.


2. Keep Functions Laser-Focused (SRP)

A function should do one thing—and do it perfectly. This is called the Single Responsibility Principle (SRP).

Good code is like a hammer. It hits ONE nail, not ten.

// Clean: One job, one focus
function calculateTotal(a, b) {
    return a + b;
}

function logTotal(user, total) {
    console.log(`User: ${user}, Total: ${total}`);
}

// Dirty: Trying to do EVERYTHING
function calculateAndLogTotal(a, b, user) {
    let total = a + b;
    console.log(`User: ${user}, Total: ${total}`);
}
Enter fullscreen mode Exit fullscreen mode

When you mix tasks, you mix CONFUSION with disaster.


3. Stop Using Comments as a Crutch

You don’t explain what a door does EVERY time someone walks into a room. Your code should work the same way.

// Clean: Self-explanatory
let userAge = 25;

// Messy: Needs an explanation
let a; // This means "age of the user"
Enter fullscreen mode Exit fullscreen mode

Comments aren’t bad, but if your code can’t stand on its own, you’ve already failed.


4. Make It Readable

If someone reading your code feels like they’re solving a riddle, you ALREADY became a troublemaker.

// Clean: Reads like a story
if (isLoggedIn) {
    console.log("Welcome!");
} else {
    console.log("Please log in.");
}

// Messy: Feels like chaos
if(isLoggedIn){console.log("Welcome!");}else{console.log("Please log in.");}
Enter fullscreen mode Exit fullscreen mode

Readable code isn’t just for others—it’s for you six months from now.


5. Test Everything You Write

If you’re too lazy to write tests, DON'T complain when your code breaks.

class Calculator {
    add(a, b) { return a + b; }
    subtract(a, b) { return a - b; }
}

// Test it (Unit Test)
const calculator = new Calculator();
console.assert(calculator.add(2, 3) === 5, "Addition failed");
console.assert(calculator.subtract(5, 3) === 2, "Subtraction failed");
Enter fullscreen mode Exit fullscreen mode

Tests are your insurance policy. Ignore them, and you’re gambling with your time.


6. Beware of Dependencies

Dependencies are like DEALS. Get the RIGHT ones, and you WIN. Choose badly, and you’re locked into something you’ll regret.

// Dependency: Sending emails with Nodemailer
const nodemailer = require('nodemailer');
function sendEmail(to, subject, message) {
    const transporter = nodemailer.createTransport({ /* config */ });
    return transporter.sendMail({ from: "you@example.com", to, subject, text: message });
}
Enter fullscreen mode Exit fullscreen mode

Avoid hardcoding dependencies. Use abstraction or configuration files for secure maintenance.

This is just one example. As a developer, you may use HUNDREDS of libraries or dependencies.

I am not saying you should not rely on them, nowadays it is hard to avoid them. But you should be very careful BEFORE installing them in your coding projects.

You should check the security, performance, quality or functionality of an organization's software systems. Because they sometimes contain risks that can ruin your ENTIRE project.

Always CONTROL your tools, don't let them control YOU.


7. Organize Project Like a Boss

A well-organized project is the difference between a garage sale and a high-end boutique.

myProject
├── src
│   ├── components
│   ├── services
│   ├── utils
└── tests
Enter fullscreen mode Exit fullscreen mode

Here is how EACH folder should be organized for this project:

Image of clean code project structure by shahan

If your codebase looks like a junk drawer, you’ve already lost the respect of your future self.

An Email App's Solid Project Structure:
Let's say you are building an application that sends emails to users. Your boss-like infrangible SOLID project structure should look like this:

Image of email app clean code project structure by shahan


8. Be Consistent with Formatting

Don’t code like a person with 10 personalities. Be consistent with your formatting.

Use tools like Prettier or ESLint to enforce your CONSISTENT style. If every file looks different, you’re creating chaos that NO ONE wants to fix.

I would say, consistency in formatting is a fundamental principle of clean code as it guarantees readability.

Have a look...

Image of consistent formatting snippets from clean code zero to one book

Use 2 or 4 spaces for indentation consistently throughout your codebase. Avoid tabs to maintain uniformity across different editors.

Keep lines to a maximum of 100-120 characters to prevent horizontal scrolling and improve readability.

Group related logic together and separate blocks of code with blank lines to highlight their purpose.

Finally, avoid over-aligning code; instead, let indentation naturally guide the flow of logic.


9. Stop Hardcoding Values

Hardcoding is laziness disguised as effort. Have a look:

// Bad: Hardcoded and rigid
function createUser() {
    const maxUsers = 100;
    if (currentUsers >= maxUsers) throw "Too many users!";
}

// Clean: Dynamic and flexible
const MAX_USERS = 100;
function createUser() {
    if (currentUsers >= MAX_USERS) throw "Too many users!";
}
Enter fullscreen mode Exit fullscreen mode

So, hardcoding is the shortcut that sends you off a cliff.


10. Keep Functions Short

If your function is longer than 20 lines, it’s probably trying to do too much. Break it down.

function updateCart(cart, item) {
    addItemToCart(cart, item);
    let total = calculateTotal(cart);
    logTransaction(item, total);
    return total;
}

function addItemToCart(cart, item) {
    cart.items.push(item);
}
Enter fullscreen mode Exit fullscreen mode

Short functions are sharp functions. They hit their mark EVERY time.


🎄🎁Christmas Giveaway!

ANYONE can write messy code. Even AI can churn out garbage.

But writing clean code? That’s the skill that separates the amateurs from the professional programmers.

You want to dominate software development? Write clean code. Simple as that.

How to write clean code then?

Let me tell you something—what you just read in this article is NOTHING more than a droplet from the ocean of knowledge in my book, Clean Code Zero to One.

clean code zero to one book cover

These 10 rules? They’re just the SURFACE.

The book digs deep into EVERY principle, EVERY rule, and EVERY technique, explained in ways so clear and detailed that you’ll NEVER forget them.

I’ve packed it with thousands of digital illustrations and real-world scenarios that don’t just teach you—they pull you into the world of clean coding like nothing you’ve ever seen.

clean code zero to one book pages

The truth is: messy coders don’t SURVIVE. They drown in their own chaos. Clean coders DOMINATE. They write software that stands the test of time, and they NEVER struggle with bugs they can’t fix or features they CAN'T add.

If you’re SERIOUS about manifesting the WAY you write code, this book isn’t an option—it’s a must-have.

And because it’s Christmas, I’m making this easy for you. Use the promo code MERRYCHRISTMAS to get 50% off.

But don’t wait too long—this offer ends December 31, 2024.

Click the link below, get that book.

👉 Get Clean Code Zero to One Now

The choice is yours. You can keep writing messy code, wasting time and energy, or you can TAKE CONTROL, learn to DOMINATE your projects, and BUILD software like a BOSS.

🐦 Follow me for more: @shahancd
📨 My Weekly Newsletter: Horscoder


Read more: writing clean, reusable components in React

Top comments (0)