DEV Community

Cover image for Clean Code Applied to JavaScript — Part II. Variables
Carlos Caballero
Carlos Caballero

Posted on • Originally published at carloscaballero.io

Clean Code Applied to JavaScript — Part II. Variables

This post is the second of an interesting series of posts that will delve into the well-known topic that is “Clean Code” but applied to JavaScript.

In this series, we are going to discuss the classic tips around clean code that every programmer should know but applied to a specific JavaScript/TypeScript language.

Introduction

In this post, we are going to present the fundamental tips and advice to generate clean code focusing on the most basic element when we are programming: The variables.

All our examples are illustrated with JavaScript but these good practices should be applied in any programming language, including the programming languages “closest to the metal”. I do this comment because I have had discussions with colleagues who are working in languages like C or Go and do not like applying these practices arguing that in their programming language “nobody” does. Then, I always answer that someone has to be the first to break the deck as long as it is to try to improve. However, this comment gives for long and pleasant conversations between colleagues in which advantages and disadvantages of these practices are discussed.

Therefore, we start with the tips to generate good code applied specifically to the variables.

Use intention revealing names

Variable names must reveal the intention of that variable. That is, we should not have variables with names like “x” or “y” unless we are developing mathematical software. In the context of mathematics those names are accurate but in the case that we are storing other information in a variable it should be named other way since the variable itself must reveal what you want to do.

In the first case, if we call a variable with the name x, how can we know what information is stored in it? It can not!

In the second case, we continue to maintain the name without revealing the intention and add a comment. Why do we want to add a comment to a bad variable name? The solution is much simpler a priori, and it is to give the variable a proper name.

Now comes the fun, how long does it take for parents to give a name to a child? Well, to find suitable names we will be a long time, but the best of all is that we, with the support of our IDEs, can constantly rename the variables until we find a more appropriate name.

    const x; // What it is?!
    const x; // User information
    const user;

Use pronounceable names

If the name of a variable has to reveal an intentionality, we must be able to pronounce it. If we go back to one of the main practices of clean code, which consists in generating human readable code, we must think that it is essential that we can pronounce the variables. Therefore, you should not invent acronyms for the occasion, even if they seem the most cute and ingenious in the universe. You are programming with colleagues, and for your not-so-ingenious future.

Another wrong action when choosing the name of a variable is to apply diminutives by removing letters from a word. First of all, remember that we are coding in English, and that not all developers are English speakers. Therefore, why are we going to reduce its name by 3 or 4 characters? What benefit does that have? The code will be manipulated by tools (transpilators including compilers in other languages), the code will be tabulated correctly (using prettier). Therefore, putting names that are not pronounceable can only cause us to make a mental effort to deduce the intentionality of the variable.

Please do not make me think about matters that are not the focus of my business logic !!

Look at the following code, you will perfectly deduce what kind of data the class is modeling but it will require a pseudo-code between the development team or even a mental effort. Next, read the second code, which is modeling the same information but will not require mental effort to know what type of data is being stored.

    class DtaRcrd102 {
     private Date genymdhms;
     private Date modymdhms;
    }


    class Customer {
     private Date generationTimestamp;
     private Date modificationTimestamp;
    }

Don’t use the variable’s type in the name

An old practice was to use a prefix in the name of the variables specifying the type of the data. Let’s reflect on this:

  • Do we have to create a pseudo-prefix code for the types of data contained in a variable?

  • Each company has its own pseudo-code and should I learn that pseudo-code by company or by project?

  • Why do I want the typing system of a programming language if I am using it in the name of the variable?

  • What happens if I have to modify the type of data from an array to a set or a map?

  • What does that prefix give me? Is it pronounceable?

If we have a language that is typed, why do we want this prefix? But even if the language was not typed as happens in JavaScript. We are revealing in the name of the variable a concrete implementation and it is coupling us to a type of data.

That is, we are coupling the type of data or data structure to the logical concept or problem of the business to solve.

This does NOT contribute ANYTHING !!

On the contrary, it produces that the variable is not pronounceable, and if we make an improvement (adaptation of our code to a new type of data) we have to be renaming all the code. That is, this prefix is noise.

Look at the two examples in the definition of the variables. Was it really necessary to use the prefix for you to understand the content of the variable as a developer?

    const aCountries = [] 
    const sName = ‘’
    const dAmount = 3.2;


    const countries = [] 
    const name = ‘’
    const amount = 3.2;

Use the same vocabulary for the same variable’s type

This advice is not exclusively for when working as a team but this happens even when code is generated individually. Especially, at the beginning of our career as software developers.

Use the same vocabulary for the same type of data. That is, if we need to retrieve the information of a user or client. We cannot refer to the user or client differently, that is, sometimes we call it user other times customer or even the term client. More serious is when we even have a suffix added to the variable name.

Therefore, the vocabulary to be used in all software must be defined. More important is this definition when we are working as a team. It cannot be that a group of developers refers to the same concept with different names.

The following example illustrates just that, the same concept, with three different definitions. The decision must always be made to always use the same name, no matter if user, customer or client but always the same.

    getUserInfo();
    getClientData();
    getCustomerRecord();


    getUser();

Don’t add unneeded context

It is not necessary to add context of the class or package in the definition of the name of a variable.

It is very common that context is added in the name of the variable to know in which workspace this variable is located. This is not necessary, in fact, you will quickly realize when you read the code since you will find unnecessary redundancy that causes you noise when it comes to understanding the concept.

In the following example we have the definition of a car with three basic attributes and a method. In the case that we have included the context, we can observe how the word car is constantly repeated and does not contribute anything. If we eliminate the word (context) car, the code is perfectly understood; In fact, it is better understood since we have eliminated unnecessary noise.

    const Car = {
     carMake: Honda,
     carModel: Accord,
     carColor: Blue
    };

    function paintCar(car) {
     car.carColor = Red;
    }



    const Car = {
     make: Honda,
     model: Accord,
     color: Blue
    };

    function paint(car) {
     car.color = Red;
    }

Don’t use magic number and strings

When you are programming code you should NEVER have numbers and text strings written in the source code (hardcode) that have a value. These are referred to as magic numbers or magic chains. What does that number mean? Do I have to decipher it? You realize, that you make me think again outside the focus of my business logic.

Therefore, those magic numbers or chains must be frequently stored in constants which receive a name that specifies the intentionality of that magic number.

Therefore, remember that writing numbers or text strings that have a meaning at the level of business logic causes noise if they do not have a given name in a variable or constant.

The following example shows how the assignment of a number makes us think what that number can mean. In addition, text strings are dangerous if instead of writing *Administrator *you write *Adminitrator *in an erroneous way the software will stop working properly without knowing why.

    // What the heck is 86400000 for?
    setTimeout(blastOff, 86400000);
    user.rol = Administrator;




    const MILLISECONDS_IN_A_DAY = 86400000;
    const ADMINISTRATOR_ROL = Administrator;

    setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
    user.rol = ADMINISTRATOR_ROL;

Conclusions

In our first steps as developers, we do not notice the name of the variables because normally we start developing scripts or codes in which we work alone. Our first applications are to learn how to program and once they are made, we never return to them. Therefore, we do not need to read our own source code.

However, when we are working on a software application that will be maintained over a considerable time or will be developed by several developers, it is when we will have the need to read and reread our source code. At this time, the name we assign to our variables will give us a touch of quality and clean code.

In this post, we have reviewed some of the fundamental points when selecting the name of our variables. If you are learning to program, write them down because they will save you a lot of mental efforts in the future. In case you have a long professional career, you will observe that naturally you have reached these conclusions by constantly reading code.

Remember, the points we have addressed are the following:

  • Use intention revealing names

  • Use pronounceable names

  • Don’t use the variable’s type in the name

  • Use the same vocabulary for the same variable’s type

  • Don’t add unneeded context

  • Don’t use magic number and strings

Top comments (8)

Collapse
 
deathshadow60 profile image
deathshadow60

I'm adding this one to my list of articles I recommend for beginners, as it's exactly the type of stuff I'm always talking about where some developers seem to -- on purpose -- make their code needlessly cryptic and hard to follow.

Whilst meant for C programmers, I've used this one for over a decade whenever people ask about good practices. It promotes many of the same ideas.

ibm.com/developerworks/library/l-c...

Collapse
 
carlillo profile image
Carlos Caballero

Thanks!!

Collapse
 
ionline247 profile image
Matthew Bramer

I was waiting for booleans...
They're really easy to read, if they're prefixed with a verb. e.g

const isMonday
const hasCoffee
const shouldPost
Enter fullscreen mode Exit fullscreen mode
Collapse
 
carlillo profile image
Carlos Caballero

Yes!

I forget it. The best name to Boolean are there (in my experience) 🙃

Collapse
 
murrayvarey profile image
MurrayVarey

Use the same vocabulary for the same variable’s type

This is a great point that is rarely mentioned. I sometimes find myself doing this wrong -- using different terms for the same concept, often with the intention to make them distinct. Really, I've just made the code confusing.

Excellent article. Naming may seem trivial, but it is so important. Such a small thing which can make code far more readable. Anyone who creates good variable names is okay by me!

Collapse
 
bknack profile image
Bruce Knack

As you know, JavaScript is not a typed language. I found it extremely useful to preface my variable names with type information.

In addition to its primary purpose, I found that it lets me use the same variable name in the same context but with different prefaces. This makes reading the code even easier.

I would love to hear about a better alternative for untyped languages like JavaScript.

Collapse
 
dean profile image
dean

Here's what Russ Cox says about variable naming: research.swtch.com/names

It's a short read with a lot of good discussion in the comments.

Collapse
 
carlillo profile image
Carlos Caballero

Thanks!! That link was awesome!