不求谌解

不求谌解

💻 Web Dev / Creative 💗 ⚽ 🎧 🏓
twitter
github
jike
email

The Art of Variable Naming

title: The Art of Naming Variables
date: 2019-07-26
categories:


image

This is a recently translated article1 (also my second translated article👏), with some minor modifications in certain parts of the article, as well as additional content based on the original text. I hope it doesn't mislead anyone. Have Fun!

In computer science, there are only two hard things: cache invalidation and naming things. - Phil Karlton

Naming things can be very difficult at times. But it is worth our effort to study it. Looking back, have you ever seen code like this before?

const convertObj = (x, y, z) => {
    const k = Object.keys(x);
    return k.map((key) => {
        return {
            [y]: key,
            [z]: x[key],
        }
    });
}

Can you immediately understand what it is doing? Of course, after reading through this code line by line, you may understand what it is trying to express. However, if the variables in this code were named more elegantly, we would find it easier to understand the content.

Good variable naming is very important, especially in dynamically typed languages, because we cannot rely on predefined variable types to help us understand the exact meaning of the variable. However, if we can use good naming conventions in dynamically typed languages, the code will be more readable compared to statically typed languages.

Next, I will share some basic rules about naming conventions, based on my experience over the years. I will provide examples by comparing different variable types. Let's start with arrays.

Arrays#

An array is an ordered collection of data, where the basic types of each item are roughly the same. Since an array contains multiple variable values, the variable names should be meaningful and in plural form.

// bad
const fruit = ['apple', 'banana', 'cucumber'];
// okay
const fruitArr = ['apple', 'banana', 'cucumber'];
// better
const fruits = ['apple', 'banana', 'cucumber'];
// very good - "names" implies that the array contains strings
const fruitNames = ['apple', 'banana', 'cucumber'];
// elegant
const fruits = [{
    name: 'apple',
    genus: 'malus'
}, {
    name: 'banana',
    genus: 'musa'
}, {
    name: 'cucumber',
    genus: 'cucumis'
}];

Booleans#

Boolean type has only two values, true or false. When naming variables, using prefixes like 'is', 'has', or 'can' will help readers understand the variable type.

// bad
const open = true;
const write = true;
const fruit = true;

// good
const isOpen = true;
const canWrite = true;
const hasFruit = true;

When dealing with predicate functions (functions that return a boolean value), it can be annoying to name the variable after the named function.

const user = {
  fruits: ['apple']
}
const hasFruit = (user, fruitName) => {
  user.fruits.includes(fruitName)
}
// How should we name this boolean variable?
const x = hasFruit(user, 'apple');

Since we have already added the prefix 'has' to the function name, we cannot name the boolean variable 'hasProjectPermission' in this case. In this situation, we can add 'check' or 'get' to modify the predicate.

const checkHasFruit = (user, fruitName) => {
  user.fruits.includes(fruitName)
}
const hasFruit = checkHasFruit(user, 'apple');

Numbers#

When it comes to number types, think about the words that describe numbers. Words like 'maximum', 'minimum', 'total'.

// bad
const pugs = 3;
// good
const minPugs = 1;
const maxPugs = 5;
const totalPugs = 3;

Functions#

Functions should be named using a combination of verbs and nouns, and the name should reflect the behavior it produces on the object prototype. 'actionResource' is a naming format worth emulating. For example: 'getUser'.

// bad
userData(userId);
userDataFunc(userId);
totalOfItems(items);
// good
getUser(userId);
calculateTotal(items);

In general, I use 'to' as a prefix for function names to indicate the conversion of variable values.

// I like it
toDollors('euros', 20);
toUppercase('a string')

When iterating through items, I often use this common naming convention. When a function receives a parameter, it should use the singular form of the array name.

// bad
const newFruits = fruits.map(x => {
  doSomething(x);
});
// good
const newFruits = fruits.map(fruit => {
  doSomething(fruit)
})

Back to the beginning#

Refactor the code at the beginning

const arrayToObject = (array, id, name) => {
  const arrayList = Object.keys(array);
  return arrayList.map((key) => {
      return {
          [id]: key,
          [name]: array[key]
      }
  });
}

Self-reflection#

// Previous naming => rsshub project
// 1. Get article list
const list = $('.con_list li h3')
      .find('a')
      .map((i, e) => $(e).attr('href'))
      .get();
// 2. Send requests to the article links obtained from the iteration
const res = await got.get(itemUrl);

// Improved naming
const articleLists = $('.con_list li h3')
      .find('a')
      .map((i, list) => $(list).attr('href'))
      .get();

const responseData = await got.get(itemUrl);

Footnotes#

  1. Original article link

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.