Clean Code Applied to JavaScript — Part II. Variables

This article is part of the “Code Clean” series, which explores how to write clean JavaScript code. In this series of articles, we’ll discuss the neatness of JavaScript/TypeScript code that programmers should know and should know.

Introduction to the

In this article, we’ll cover basic tips and advice for writing clean code, focusing on the most basic element of code — variables.

All of the examples in this article are implemented in JavaScript, but these good practices apply to any programming language, including “closest to hardware” (CTM) programming languages. Why make this point in particular? I’ve had discussions with colleagues who use C or Go for development at work, but don’t like the idea of applying these practices to development, even assuming that “nobody” in the programming language they use does it. And my answer is, it takes action to make a difference. Nevertheless, we had a long discussion about the pros and cons of these practices.

Next, we begin to show you how to apply these techniques to variables in your program.

The variable name should be true to its name

The name of a variable must describe the function and purpose of the variable. That is, we should not use names like X or y as variable names unless we are developing mathematical software that is accurate in a mathematical context. In other cases, you should avoid this type of variable name because it fails to describe the true purpose of the variable and makes the code difficult to understand.

First, if we call a variable named x, can we immediately know what it does? Can’t!

Second, we keep the name and comment it out. But why comment a variable name that is not canonical? Obviously, there is a simpler solution to this problem, which is to give the variable an appropriate name.

Now the interesting thing is, how long does it take parents to choose a name for their child? Similarly, it takes a long time to find the right variable name. But most importantly, with the support of the IDE, we can keep renaming variables until we find a more appropriate name. Choosing the right name takes time, but it’s easy to know what’s going on.

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


const user;
Copy the code

Variable names can be read

If the name of a variable makes sense, the best thing is that we can pronounce it. Going back to one of the most important practices of clean code, which is generating human-readable code, I think it’s essential to be able to pronounce variables. Therefore, acronyms should not be used in such situations, even if they seem very clever.

Another mistake when choosing the name of a variable is to remove certain letters from a word that are difficult to pronounce using these abbreviations. First of all, we’re coding in English, and not all developers speak English. So why should we reduce its name by three or four characters? What’s the good of that? The code is manipulated by tools (translators include compilers from other languages) and eventually formatted correctly (using Prettier). Thus, lumping together unpronounciable names only makes it harder to infer the purpose of the variable.

Please don’t make me think about things that are not the focus of business logic!!

Looking at the first piece of code below, you can probably figure out what type of data the class is creating, but it’s a great test of rapport between team members. In the second piece of code, it defines the same data, but it doesn’t take any brainpower to let people know what the variable is for.

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


class Customer {
  private Date generationTimestamp;
  private Date modificationTimestamp;
}
Copy the code

Do not use variable types in names

Using datatypes as prefixes in variable names is an old practice, but let’s reflect on it now.

  • Do variable names have to be prefixed with type?
  • Every company and project has its own prefix specification, so how do you learn and write this code?
  • If I use a programming language’s type system in variable names, why use it?
  • What happens when the data type of a variable changes, such as Array to Map?
  • What does this prefix give us? Is it pronounceable?

If our language is typed, why do we have this prefix? But even if the language is not typed, as happens in JavaScript. We reveal a concrete implementation in the name of the variable that ties us to the type of data.

In other words, we are associating data types with business logic.

It makes no sense!

On the contrary, it makes variables unpronounciable, and if we make improvements (adapting our code to the new data types), we have to rename everything. In other words, the prefix is noise.

Take a look at two examples from variable definitions. As a developer, do you really need to use this prefix to understand the content of a variable?

const aCountries = [];
const sName = ' ';
const dAmount = 3.2;


const countries = [];
const name = ' ';
const amount = 3.2;
Copy the code

Use the same vocabulary for variables of the same type

This advice is not specific to working within a team; it can happen even when code is generated separately. Especially at the beginning of our careers as software developers.

Use the same vocabulary for the same type of data. If we need to retrieve information about a user or customer, we cannot address the user or customer differently. That is, you can’t call it user sometimes, call it Customer sometimes, or even the word client. It is even less desirable to add an extra suffix to the variable name.

Therefore, in software development, it is necessary to standardize or define the terms and terms of the industry. This specification or definition is especially important when it comes to team development, to avoid having a bunch of developers using different names for the same concept.

The following code is a good example. There are three different definitions of the same concept. The user, Customer, or client name must be the same from beginning to end.

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


getUser();
Copy the code

Do not add unnecessary context

There is no need to add a class or package context to the variable name.

It is common to add context to a variable name so that you know which workspace the variable resides in. In fact, when we read the code, we quickly realize that this is completely unnecessary. This unnecessary redundancy can cause some distraction in the process of understanding code.

In the following example, a Car is defined with three basic properties and a method. In the case of variables containing context, we can observe that the word CAR is repeated over and over without any effect. If we drop the word car (context), the code is perfectly understandable; In fact, the code is easier to understand now that we’ve removed the 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';
}
Copy the code

Don’t use magic numbers and strings

When writing code, you should never use numbers or text strings directly in source code, which are also commonly referred to as magic numbers. What does this number mean? Do I have to explain this number? This forced us to think beyond our business logic.

Therefore, these magic numbers or strings must be stored in constants and their purpose expressed by their names. At the business logic level, not having an exact name for a meaningful number or text string can cause noise.

In the following example, the number 86,400,000.00 will leave you scratching your head. In addition, text strings are also dangerous, for example, if the Administrator is miswritten as Adminitrator one time and the code causes problems, it is not easy to flush out errors.

// 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;
Copy the code

conclusion

When we’re starting out as developers, we probably don’t notice variable names, because we’re usually working alone when we start developing scripts or code. And our focus is on how we code, and once the project is developed, we don’t read our own source code.

However, when we develop software that takes a long time to maintain, we need to read and re-read the source code. At this point, properly named variables will lead to high-quality, clean code.

In this article, we reviewed some of the basics of naming variables. If you are learning to program, write them down, because they will save you a lot of effort in the future. If you’ve had a long career, you’ll find that by constantly reading code, you’ll come to these conclusions naturally.

Keep in mind that the main points of our discussion are as follows:

  • The variable name should be true to its name
  • Variable names can be read
  • Do not use variable types in names
  • Use the same vocabulary for the same type of variable
  • Do not add unnecessary context
  • Don’t use magic numbers and strings

Related articles

  • The Way to Clean JavaScript Code – Exception Handling
  • The way to clean JavaScript code – Complex judgment
  • The Way to clean JavaScript Code – Comments
  • The Way to clean JavaScript Code – Functions
  • Simple practices for writing clean React code
  • Simple tips for writing a compact React component

Click on KooFE’s front End Team to reply to “Code Cleanliness” for a chance to receive a code Cleanliness book.