How to Write Clean Code – Tips for Developers With Examples
How to Write Clean Code – Tips for Developers With Examples
Now, think about writing messy code – it’s just as confusing, if not
more!
On the other hand, clean code is like an organized room: you can Donate
Forum
easily find what you need, understand what’s happening, and get
Learn to code — free 3,000-hour curriculum
things done faster.
Let’s have a look at this graph. It shows two different ways of writing
code and how they affect the time it takes to add more lines:
1. ⚠️ Quick & Dirty Code (Red line): This is when you write
code quickly without planning or organizing it well. At first, it
may seem faster, but as more lines are added, it becomes
harder to understand and fix. So, over time, it takes longer
and longer to add each new line.
11. Conclusion
Example:
// Good
let numberOfUsers = 5; // Clear and easy to understand
// Bad
let b = 5; // Vague and unclear
💡 Naming Tips
Variables: Use nouns that describe the data, like userAge or
totalAmount .
This keeps your functions short and focused which makes them
easier to read, test, and maintain.
Let’s say you want to calculate a total and return an object with
extra information, like who calculated it and when. Instead of adding
these directly into calculateTotal , we can use a second function.
Example:
// Good Code
if (isLoggedIn) {
console.log("Welcome!");
} else {
console.log("Please log in.");
}
// Bad Code
if(isLoggedIn){console.log("Welcome!");}else{console.log("Please
By testing small, individual parts (like functions), you can catch bugs
early and prevent them from spreading to other parts of the code.
Concretely, unit tests are actually mini quality checks for each part
of your code to ensure they’re working as intended.
🍎 Real-world Example:
Let’s look at how to test a complex JavaScript object with multiple
methods, using a Calculator class as an example.
This approach will help you see why it’s important to keep each
method focused on one task and ensure each one works correctly
through unit testing.
class Calculator {
constructor() {
this.result = 0;
}
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
Forum Donate
multiply(a, b) {
Learn to code — free 3,000-hour curriculum
return a * b;
}
divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
}
As you can see, each method performs one specific operation. The
divide method has additional logic to handle division by zero,
which would otherwise cause an error.
Now, we’ll write unit tests to confirm that each method behaves as
expected. 🔬
🧪 Writing Unit Tests for Each Method
To test our Calculator class, we can write unit tests that cover
normal cases as well as edge cases. Here’s how we would set up
tests for each method:
You can see that if any method fails, the test will produce a clear
error message, allowing us to quickly identify and fix the issue.
Testing methods individually helps us catch bugs early and maintain
reliable, clean code as the project grows.
Example:
const mailOptions = {
from: '[email protected]',
to: to,
subject: subject,
text: message
};
return transporter.sendMail(mailOptions);
}
Even though dependencies are useful, you should try to avoid over-
dependence on external software or libraries. Use dependencies
only when they simplify your work or add important functionality.
Managing dependencies effectively is key to writing clean
Forumcode. Donate
Here are some tips:
Learn to code — free 3,000-hour curriculum
You can create a wrapper function that abstracts away the details of
email sending. This way, you can change the underlying email
service or remove the dependency on Nodemailer without affecting
the rest of your code.
// Example usage
sendEmail('[email protected]', 'Test Subject', 'Hello, this i
.then(() => {
console.log('Email sent successfully!');
})
.catch((error) => {
console.error('Error sending email:', error);
});
🗝️ Key points:
1. Core Functions: The sendEmail , createTransporter , and
createMailOptions functions are separate, allowing you to
modify one without affecting the others.
myProject
├── src
│ ├── components
│ ├── services
│ ├── utils
└── tests
2. src (Source): This folder holds all the source code for your
project. It’s where you’ll spend most of your time coding.
services
├── emailService.js
├── userService.js
└── productService.js
utils
├── formatDate.js
├── validateEmail.js
└── generateId.js
tests
├── emailService.test.js
├── userService.test.js
└── component.test.js
myEmailApp
├── src
│ ├── components
│ │ ├── EmailForm.js
│ │ └── SuccessMessage.js
│ ├── services
│ │ └── emailService.js
│ ├── utils
│ │ └── validateEmail.js
└── tests
├── emailService.test.js
└── EmailForm.test.js
Establish a pattern for how you write your code, such as using two
spaces for indentation or always including a line break before
comments.
function createUser(name) {
let numberOfUsers = getCurrentUserCount(); // Get the current
if (numberOfUsers >= MAX_USERS) {
return 'User limit reached.';
}
// Code to create the user
return 'User created.';
}
{
"maxUsers": 100,
"emailService": {
"service": "gmail",
"user": "[email protected]",
"pass": "your-email-password"
}
}
function createUser(name) {
let numberOfUsers = getCurrentUserCount();
if (numberOfUsers >= config.maxUsers) {
return 'User limit reached.';
}
// Code to create the user
return 'User created.';
}
Forum Donate
return total;
}
While this function might look manageable now, it can quickly grow
if more tasks are added, making it harder to debug and maintain.
if (discountCode) {
total = applyDiscount(total, discountCode);
}
logTransaction(item, total);
return total;
}
function calculateTotal(cart) {
return cart.items.reduce((total, cartItem) => total + cartIte
}
🧩 Let me explain:
1. addItemToCart : This function is now responsible only for
adding an item to the cart. It’s simple, with a clear purpose.
2. calculateTotal : This function calculates the totalForum
price of Donate
all items in the cart. It’s easier to read and understand, and if
Learn to code — free 3,000-hour curriculum
you need to update the way totals are calculated, you only
have to modify this function.
structure.
These principles make coding less about writing and more about
designing solutions. Writing clean code is a skill that grows with
practice, so keep learning and improving over time.
🔌 A Note on Dependencies
Instead of hardcoding dependencies directly into your code, use
package managers like npm (for JavaScript) or pip (for Python) to
manage them. This way, you can easily update or remove them when
needed.
Conclusion 🏁
Writing clean code is like building a strong foundation for a house. It
keeps everything in order, making it easy to add new features or fix
issues as your project grows.
With these tips, you can start developing habits that will make your
code more readable, maintainable, and enjoyable to work on.
If you read this far, thank the author to show them you care.
Say Thanks
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Mobile App
Our Charity
About Alumni Network Open Source Shop Support Sponsors Academic Honesty