Writing code that only needs to be used once can be done however you want to write. But, in most cases, adhering to best practices and maintaining clean code is essential.
Remember, your code will likely be read by another developer, or even yourself, at a later date. When that time comes, your code should be self-explanatory. Every variable, function, and comment should be precise, clean, and easy to understand. This approach not only facilitates easier maintenance but also promotes collaboration and efficiency within your development team.
So, when someone (or you) comes back to add or modify your code, it will be easy to understand what each line of code does. Otherwise, most of your time will be spent just trying to understand the code. The same issue will arise for a new developer working on your codebase. They will not understand the code if it is not clean. Therefore, it is very important to write clean code.
What is Clean Code ?
Clean code is basically refers to the code which is
- Easy to Understand
- Easy to Debug
- Easy to Maintain
- Comments are well written, short and understandable
- No duplicate(Redundant) code and follows KISS rule (Keep it simple, Stupid!)
With that for writing clean code developer has to maintain consistency in code and developer needs to follow best practices for the particular language.
Why Clean Code is important ?
When teams follow clean code principles, the codebase becomes easier to read and navigate. This helps developers quickly understand the code and start contributing. Here are some reasons why clean code is important.
1. Readability and maintenance: It is easy to read and understand the code when it is well written, has good comments and follows best practices. Once issue or bug come you exactly know where to find it.
2. Debugging: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues.
3. Improved quality and reliability: Clean code follows best practices of particular languages and prioritizes the well structured code. It adds quality and improves reliability. So it eliminates the errors which might comes due to buggy and unstructured code.
Now that we understand why clean code is crucial, let's dive into some best practices and principles to help you write clean code.
Principles of Clean Code
To create great code, one must adhere to the principles and practices of clean code, such as using small, well-defined methods.
Let's see this in details.
1. Avoid Hard-Coded Numbers
Instead of using value directly we can use constant and assign that value to it. So that in future if we need to updated that value we have to update it at one location only.
Example
function getDate() {
const date = new Date();
return "Today's date: " + date;
}
function getFormattedDate() {
const date = new Date().toLocaleString();
return "Today's date: " + date;
}
In this code, at some point there is change that instead of "Today's date: " need becomes "Date: ". This can be improved by assigning that string to one variable.
Improved code:
const todaysDateLabel = "Today's date: ";
function getDate() {
const date = new Date();
return todaysDateLabel + date;
}
function getFormattedDate() {
const date = new Date().toLocaleString();
return todaysDateLabel + date;
}
In above code it is becomes easy to change the date string when ever needed. It improves maintainability.
2. Use Meaningful and Descriptive Names
Instead of using common variable names everywhere we can use little bit more descriptive names which is self explanatory. Variable name itself should be define the use of it.
Names rules
- Choose descriptive and unambiguous names.
- Make meaningful distinction.
- Use pronounceable names.
- Use searchable names.
- Replace magic numbers with named constants.
- Avoid encodings. Don't append prefixes or type information.
Example
// Calculate the area of a rectangle
function calc(w, h) {
return w * h;
}
const w = 5;
const h = 10;
const a = calc(w, h);
console.log(`Area: ${a}`);
Here the code is correct but there is some vagueness in code. Let see the code where descriptive names are used.
Improved code
// Calculate the area of a rectangle
function calculateRectangleArea(width, height) {
return width * height;
}
const rectangleWidth = 5;
const rectangleHeight = 10;
const area = calculateRectangleArea(rectangleWidth, rectangleHeight);
console.log(`Area of the rectangle: ${area}`);
Here every variable names are self explanatory. So, it is easy to understand the code and it improves the code quality.
3. Only use comment where is needed
You don't need to write comments everywhere. Just write where it is needed and write in short and easy to understand. Too much comments will lead to confusion and a messy codebase.
Comments rules
- Always try to explain yourself in code.
- Don't be redundant.
- Don't add obvious noise.
- Don't use closing brace comments.
- Don't comment out code. Just remove.
- Use as explanation of intent.
- Use as clarification of code.
- Use as warning of consequences.
Example
// Function to get the square of a number
function square(n) {
// Multiply the number by itself
var result = n * n; // Calculate square
// Return the result
return result; // Done
}
var num = 4; // Number to square
var squared = square(num); // Call function
// Output the result
console.log(squared); // Print squared number
Here we can see comments are used to define steps which be easily understand by reading the code. This comments are unnecessary and making code cluttered. Let's see correct use of comments.
Improved code
/**
* Returns the square of a number.
* @param {number} n - The number to be squared.
* @return {number} The square of the input number.
*/
function square(n) {
return n * n;
}
var num = 4;
var squared = square(num); // Get the square of num
console.log(squared); // Output the result
In above example comments are used only where it is needed. This is good practice to make your code clean.
4. Write Functions That Do Only One Thing
When you write functions, don't add too many responsibilities to them. Follow the Single Responsibility Principle (SRP). This makes the function easier to understand and simplifies writing unit tests for it.
Functions rules
- Keep it Small.
- Do one thing.
- Use descriptive names.
- Prefer fewer arguments.
- Split method into several independent methods that can be called from the client.
Example
async function fetchDataAndProcess(url) {
// Fetches data from an API and processes it in the same function
try {
const response = await fetch(url);
const data = await response.json();
// Process data (e.g., filter items with value greater than 10)
const processedData = data.filter(item => item.value > 10);
console.log(processedData);
} catch (error) {
console.error('Error:', error);
}
}
// Usage
const apiUrl = 'https://api.example.com/data';
fetchDataAndProcess(apiUrl);
In the above example, we can see a function that fetches data using an API and processes it. This can be done by another function. Currently, the data processing function is very small, but in a production-level project, data processing can be very complex. At that time, it is not a good practice to keep this in the same function. This will make your code complex and hard to understand in one go.
Let's see the clean version of this.
Improved code
async function fetchData(url) {
// Fetches data from an API
try {
const response = await fetch(url);
return await response.json();
} catch (error) {
console.error('Error:', error);
throw error;
}
}
function processData(data) {
// Processes the fetched data (e.g., filter items with value greater than 10)
return data.filter(item => item.value > 10);
}
// Usage
const apiUrl = 'https://api.example.com/data';
fetchData(apiUrl)
.then(data => {
const processedData = processData(data);
console.log(processedData);
})
.catch(error => {
console.error('Error:', error);
});
In the this example, the responsibilities are separated: the fetchData function handles the API call, and the processData function handles data processing. This makes the code easier to understand, maintain, and test.
5. Avoid Code Duplication (Follow DRY Principle - Don't Repeat Your Self)
To enhance code maintainability and cleanliness, strive to create reusable functions or reuse existing code whenever possible. For instance, if you are fetching data from an API to display on a page, you would write a function that retrieves the data and passes it to a renderer for UI display. If the same data needs to be shown on another page, instead of writing the same function again, you should move the function to a utility file. This allows you to import and use the function in both instances, promoting reusability and consistency across your codebase.
Other General Rules for writing Clean Code
- Follow standard conventions(For JavaScript Camel Case).
- Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
- Boy scout rule. Leave the campground cleaner than you found it.
- Always find root cause. Always look for the root cause of a problem.
- Write code which is easy to understand
Implement this Practices and Principles from today to write Clean Code.
Top comments (1)
nice one