Skip to main content

12 Conventions for Writing Clean Code

 Coding conventions are the style guidelines for programming. Programming best practices and principles are included in this. Here we will discuss some coding conventions.

Benefits of Following Conventions

  • Clean code
  • Quality of code
  • Readability of code
  • Makes code maintenance easier

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.” — Robert C. Martin

1. Magic Numbers

A magic number means we are assigning a number with no clear meaning. Sometimes we use a value for a specific purpose, and we don't assign the value in a meaningful variable. The problem is that when someone works with your code, then the person doesn't know the meaning of that direct value.

Magic numbers

2. Deep Nesting

Sometimes we use nested loops that are difficult to understand. The way to handle that is to extract all loops into separate functions instead.

Suppose we have an array of another array that contains another array, and we want the value of the last array. We can write a nested loop that will work for our requirements. But this is not the proper way. Here I have written a function that can do the same, but this one is much cleaner, easier, less repetitive, easier to read, and reusable.

3. Comments

This one is a kind of personal attack on someone. Comments help people to understand later, and they help other programmers to work on the same project. Comments in code mean maybe your code is not self-explanatory. Here is a famous quote about writing comments by Jeff Atwood.

“While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn’t exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with.” — Jeff Atwood

Comments should be good, but your code needs to be self-explanatory.

4. Avoid Large Functions

When a function or a class is much larger, then it is suggested to separate it into multiples. This will make our code easier, clean, easy to understand, and also reusable.

Suppose we need to add and subtract two numbers. We can do it with a single function. But the good practice is to divide them into two. When there are individual functions, then this will be reusable in the whole application.

5. Code Repetition

Repeated code means a code block that is repeated in your code more than once. This means your code portion needs to be extracted into a function.

Here is an example that we used before in point 2., deep nesting, above. Look at the first portion: We have repeated the same thing three times. The solution of making an individual function to do the same thing is the better solution; also, this is reusable.

6. Variable Naming

Camel case is the naming standard for both variables and functions, and also other identifiers. This means a name is supposed to begin with a small letter, and every first letter of the next word will be uppercase.

Both function and variable must follow the rule.

let camelCase = ''const thisIsCamelCase = () => {
//so something
}

7. Meaningful Names

A meaningful name is one of the most important conventions. Always use a meaningful name for variables, functions, and others. Choose a name that expresses the meaning of your purpose.

If we need a function that will get the user's bank information, then we must not use a name like getUserInfo or something like that. We should use getUserBankInfo to be more specific.

8. Favor Descriptive Over Concise

Try to use detail for any naming. Suppose we need a function that will find a user with their phone. Here we can use meaningful names, but there is a huge possibility of mistakes if there are other, similar functions.

We must use a detailed, meaningful name that expresses the meaning in a nutshell.

//We want a function for search user against phone no//Bad practice
const searchUser = (phone) => {
//Do something
}
//Good practice
const searchUserByPhoneNo = (phone) => {
//Do something
}

9. Use Consistent Verbs per Concept

This is one of the important naming conventions. If we need a CRUD function, we use createget, or update with the name.

If we need to get user info from the database, then the name of the function can be userInfouser, or fetchUser, but this is not the convention. We should use getUser.

//Good prancticefunction getUser(){
//do something
}

10. Use Nouns for Class Name & Use Pascal Case

Classes don't take things; they are the things. Class is mainly a blueprint for something. Don't use the verb in the class name.

Also, a class should contain Pascal case. Camel case is used for objects, so this won't be very clear if you use camel case for class.

//bad practice
class MakeCar = {
//...
}
//Good practice
class Car = {
//...
}

11. Capitalize Constant Values (SNAKE UPPER CASE)

This is another convention that we need to follow. Always use fully capitalized names for constants.

Snake uppercase means all the letters will be uppercase, and an underscore will separate all the words.

const DAYS_IN_A_YEAR = 365;

12. Avoid One-Letter Variable Names

A one-letter variable is a very, very bad thing to use. Don't use this for a variable name.

But in a loop, we use some variables with a letter, which is OK to use.

//bad practice
const q = () => {
//....
}
//good practice
const query = () => {
//....
}
//this is also okay
for(let i = 0;i < 10; i++){
//...
}

Conclusion

Following these conventions will benefit you a lot in the long run. When you write code by following them, then no matter who is also working with it, the person will understand everything on their own. Clean code is needed for both individuals and teams.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...