Good practices naming and using variables.

By Darío Rivera
Posted On in Buenas prácticas

It is common that after several years, you forget one or more aspects of what I am going to address below. Naming and using variables is often much easier in theory than in practice. However, remember that the world of development is moving too fast and what may seem like the last word today may not be tomorrow. Let's see some good practices that you should consider when using variables.

- Use names that are easy to read for humans (human-readable). Some good names would be, for example, userName, personaAge, currentDate.
- Stay away from abbreviations or short names like a, b, c unless you have a good reason to use them.
- Make sure to be concise enough with the variable's name. Names such as data, value, key, counter, number, array are almost always bad names.
- Composite variable names should be able to be read naturally, either using camel case as in userName or snake case as in user_name.
- Do not use the same variable for different purposes in the same section of code. Reusing variables is generally a bad practice. Instead, a different variable should be created for each purpose.
- Although the language allows it, you should not use non-ASCII characters to name variables.
- Use nouns or adjectives to name variables instead of verbs. To display the result of a validation, validation would be better than validate. Likewise, to identify the instance of a validator, it would be correct to use validator instead of validate. There are exceptions to the rule, we will see them later.
- Being too descriptive is also a problem. Try not to exceed 50 characters for the name of your variables.
- Be consistent with the name of the variables and the number of elements they contain. An array that contains several instances of a user object should be called users, not user.
- Using is, has, can to express a boolean value is usually a good practice. A variable that holds a permission about a user could be canRead or canWrite. If we wanted to know if a user is enabled, we could use the variable name isEnabled, or if we wanted to know if an article in a blog has comments, we could use hasComments.

Acerca de Darío Rivera


Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.