Best Coding Practices for Beginners: Writing Efficient and Maintainable Code
Coding standards are essential for writing efficient and maintainable code. If you are a beginner in programming world, it’s crucial to comprehend the importance of complying with coding standards. In this article, I will list down some of the best coding practices that can help you write clean, concise and error-free code.
- Directory structure: Directory structure of your project can play a significant role in writing clean code that is easy to understand. A clear and consistent directory structure promotes modularity, reusability, and scalability which are an essential aspects of clean code. However, there are no pre-defined rules to create an ideal directory structure because it may vary depending on the specific needs of the project. But here is a common structure that can be useful:
my-project/
├── src/
│ ├── index.html
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── app.js
│ └── img/
│ └── logo.png
├── node_modules/
├── package.json
├── README.md
├── .gitignore
└── webpack.config.js
below is a brief explanation of each directory/file and it’s purpose:
`src`: The “src” folder can serve as a primary directory for writing your application’s logic. Notice that the “css”, “js” and “images” are separated into their respective directories and there is only one index.html file at the root level of “src” folder.
`node_modules`: This is the folder where all the dependencies are installed by NPM or Yarn.
`package.json`: This file contains all the information related to your project and dependencies that it requires.
`README.md`: It contains the documentation of your project.
`.gitignore`: It tells which files and directories to be ignored while commiting your changes to the github.
`webpack.config.js`: This file contains configuration settings for a tool like webpack which can be used to compile and optimize your code.
This is a very basic idea to create an ideal directory structure that is well-organized, and easy to navigate which will eventually help to make the development process smoother and more efficient.
2. Easy to read: Write clear comments, use descriptive names for variable and functions, because it improves the readability of implemented logic. For example: If you write a code to convert a date into a specific format and added a comment like “Reformat the date as mm/dd/yy from dd/mm/yy”, other developers working on the project can understand the purpose of the function without having to examine the entire code.
3. Modular code: Modular code design is an important aspect of programming. It focuses on breaking an application into smaller, independent modules. Before writing code for any specific feature, consider the following points:
- Avoid writing duplicate code. For instance, if you are making multiple API requests from your application, it is recommended to create one shared function to define the basic request body for all of the requests. You can avoid writing same lines of code every time you need to make a request. below is a very basic use-case:
/*
shared function to send api request and return response
to the calling function.
*endpoint : the api endpoint to be requested
*reqMethod : GET/POST/PUT/DELETE
*reqParam : the request body to be sent
*/
const apiRequest = async (endpoint, reqMethod, reqParam) => {
const sendRequest = await fetch("https://abc.com/" + endpoint, {
method: reqMethod,
mode: "cors",
headers: { "Content-Type": "application/json" },
body: reqParam
});
if (sendRequest.status !== 200) {
return {
success: false,
message: "Sorry, Something went wrong."
}
} else {
return {
success: true,
message: "API call succeeded."
}
}
}
This is a reusable shared function to send as many API requests from the application without writing the same lines of code again and again. You only need to pass the required parameters to this function and that’s it.
// Example 1: save customer data request
const saveCustomerData = apiRequest("save-data",
"POST",
{
"name": "Shivani",
"email": "abc@abc.com"
}
);
// Example 2: update customer data request
const saveCustomerData = apiRequest("update-data",
"PUT",
{
"name": "Shivani",
"email": "abc@abc.com"
}
);
- It is always helpful to break large functions into smaller ones, as larger functions tend to be more complex and involve a lot of logic which make them difficult to read and comprehend. In such cases, you can split your large function into multiple smaller functions, each focusing on a specific aspect of the overall task.
4. Keep security in mind: Be mindful of the security aspects while writing code. It should not be vulnerable to hacking attempts. It is essential to incorporate appropriate client and server side validations for all the data transmitted to the server through various sources. Implementing validations will ensure that sensitive information remains protected.
5. Exception handling: It is important to ensure that your application doesn’t crash or produce any incorrect results when an error occurs. You can use try-catch block to handle exceptions in code. Additionally, implementing email notifications can be helpful in alerting you to any issues that may arise, allowing you to address them promptly and prevent any further problems.
While there are many other important considerations when writing code for any application, these five points are among the most critical to keep in mind. Adhering to coding standards is crucial for writing efficient and maintainable code, especially for beginners and keeping these points in mind will ultimately lead to clean, concise, and error-free code.