If you're in a messy room, you can’t find your keys. Clothes everywhere, books piled up.
That applied to messy code. It’s the SAME disaster, except now it’s your brain that’s LOSING its energy.
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 survive in software development. AI already writes cleaner code than you.
Fortunately, as the best creation on earth, we human beings are able to master clean code.
You can write messy code and be the person who struggles to fix every bug, getting rejected from the job interview and failing to build a manageable startup, or you can master clean code and DOMINATE every project you touch.
Clean Coder vs. Messy Coder
Here’s a graph that shows the journey of two types of coders:
- ⚠️ 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.
🐦 Early Bird Sells: 50% OFF 🚨
If you’re serious about mastering clean code and taking your programming career to the next level, then this book is for you: Clean Code Zero to One. I am offering 50% discount using the code "earlybird" — only for the first 50 copies! Plus, enjoy a 30-day money-back guarantee — no risk, all reward. Or KEEP struggling with your buggy code. I can't visit your desk to fix it for you.
Cost of Bad Code
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;
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}`);
}
When you mix tasks, you mix CONFUSION with disaster.
3. Silent Comments
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"
Comments aren’t bad, but if your code can’t stand on its own, you’ve already failed.
4. Make Your Code 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.");}
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");
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 });
}
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.
Here is how EACH folder should be organized:
If your codebase looks like a junk drawer, you’ve already lost the respect of your future self.
An Email App's Clean Project Structure:
Let's say you are building an application that sends emails to users. Your clean project structure should look like this:
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 one of the most important aspects of clean coding.
Have a look...
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.
// 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!";
}
So, avoid it at all costs. 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);
}
Short functions are sharp functions. They hit their mark EVERY time.
Read more: writing clean, reusable components in React
Top comments (10)
Great article. I do have a different perspective on the "7. Organize Project Like a Boss" section. I don't like the part where you created utility file for each utility function. Personally, I find it more practical to use a group of
utils.js
file to store all utility functions in smaller projects(which are the ~75% of all projects imo).For example, I would structure it like this.
Utils as directory which contains following groups:
Thank you for sharing your perspective. It's a valid approach, especially for smaller projects.
However, in the context of clean code principles, separating utility functions into their own files follows the rules of single responsibility and clarity.
For large or complex projects, having dedicated files for different utilities (e.g.,
authUtils.js
,formValidations.js
) make the codebase more manageable and self-explanatory at first glance.When you open a directory and see clearly labeled files, you instantly know where to find or modify a specific function.
On the other hand, a single
utils.js
file can quickly GROW into an unorganized catch-all, it harder to manage as the project grows six weeks later.Hope this was helpful.
A lot of people don't realize the cost of chosing a dependency, so I'm glad you included that, with some ways to mitigate the risk!
I always encourage using external dependencies because it's a way to greatly increase development speed, but it's important to check a few things before blindly diving in. For example, you should check how many people have contributed to it and if the latest version has any (critical) vulnerabilities on npm audit or snyk.
It's also important to first test it in a small side project, to see if it really does what you expect it to do, so you dont realize 3 weeks later, that it doesn't integrate at all, with something else you need in your project.
That's a great idea, man! checking how many people have contributed and testing dependencies in a small project may seem a side hustle but it's really worth it.
I using almost clean code as possible ( quick & dirty ) because my time frame are very limited when I am on a hackhaton.
... but the help of JSDoc ...
Sometimes, writing (quick & dirty) code makes sense, especially in a hackathon where speed and competitiveness are the priority. Showcasing your ability to deliver results fast, even if clean and manageable code takes a backseat.
But.. when you move beyond hackathons and start building real-world apps, (quick & dirty) code becomes a liability.
The same shortcuts that save time during a hackathon will slow you down during debugging, scaling, or collaborating.
for you point 4 , already the extentions as pretty formatter in VS will do it for you
not every developer writes in VS code. Sometimes you have to write in notepad (e,g. technical interview).
Thankyou have much
Keep it Simple and Unified. Only simple can unity, only unity can be truly simple.
Another 10 Principles