šŸ“’
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript ā€Šā€”ā€Šthis keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (ā€˜ ’) and double quotes (ā€œ ā€) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • Introduction
  • 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 Numbers and Strings
  • Conclusions

Was this helpful?

  1. JavaScript Variables

Clean Code for JS Variables

Introduction

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 make 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.

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 another 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? We 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 take 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 intentionality, we must be able to pronounce it. If we go back to one of the main practices of clean code, which consists of 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 cutest and most 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 three or four 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.

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 makes it so 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 exclusive for when you’re 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, it doesn’t matter if that is 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 as 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 Numbers 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 have made me think again outside the focus of my business logic.

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

Therefore, remember to write numbers or text strings that have a meaning at the level of business logic that 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 of 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

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 numbers and strings.

PreviousJS Operators Part ThreeNextJavaScript Scopes

Last updated 5 years ago

Was this helpful?