In this series, there are many excerpts from the book, all of which I think are worth sharing. Of course, there will also be personal reflections, as a learning record and simple to share.

Take each variable name seriously. You should name variables with the same care you would name your first child. – order

Worthy of the name

Sure, choosing a good name takes time, but it can save more time than it takes. Pay attention to naming, and when you have a better name, replace the old one, and the people who read your code (and you, of course) will be happier. In general, a name should have a lot of meaning wrapped up in it, and if a name needs to be annotated, it’s not worthy of the name. Let’s take an example: let d; // Elapsed time in days the variable name D has no meaning as it does not evoke a sense of elapsed time, let alone elapsed by the day. We should select a name that specifies the object and unit of measurement. \

let elapsedTimeInDays;
let daysSinceCreation;
let daysSinceMondification;
let fileAgeIndays;
Copy the code

Choosing a name that reflects the original meaning makes it easier to understand and modify the code. Let’s look at another example:

function getThem(){
    const list1 = [];
    for(let x of theList){
        if(x[0= = =4) list1.push(x)
    }
    return list1;
}
Copy the code

The above code is not complicated and the code format is reasonable, but after reading it, I feel confused. The problem is not the brevity of the code, but the ambiguity of the code: the degree to which context is not explicitly represented in the code. The code above gives us a lot of confusion:

  1. What are the data types in theList?
  2. What is the significance of theList subscript 0?
  3. What does the value of 4 mean?
  4. What is the use of the returned list?

The answers are not in the snippets, but the snippets are where they belong. Let’s say we’re developing a minesweeper game, and we find that the disk is a list of cells called theList, so change the name to gameBoard. On the disk, each cell is represented by a simple array. We also find that the 0 subscript entry is a state value, and that a state value of 4 means “marked”. Change the code to a meaningful name and you will get a corresponding degree of improvement:

function getFlaggedCells() {
 const flaggedCells = []
 for (let cell of gameBoard) {
   if (cell['STATUS_VALUE'] === FLAGGED) flaggedCells.push(cell)
 }
 return flaggedCells
}
Copy the code

As you can see, the structure and logic of the code hasn’t changed at all, but by changing the naming, the code has become much clearer. One step further is to wrap the cell into a class that masks the number of FLAGGED by one function, isFlagged:

function getFlaggedCells() {
  const flaggedCells = []
  for (let cell of gameBoard) {
    if (cell.isFlagged()) flaggedCells.push(cell)
  }
  return flaggedCells
}
Copy the code

As you can see, the process isn’t complicated, just optimizing the naming of variables and pulling out a class, but the code is billions of points more readable, which is the power of good naming.

Make meaningful distinctions

Not much, but examples:

function copyList(list1, list2) {
  for (let i = 0; i < list1.length; i++) {
    if (list1[i].checked) list2.push(list1[i])
  }
}
Copy the code

In fact, the method is not the most horrible name, I actually encountered in the project directly list1,list2,list3 such names, without comments ~~~

Now if we change the name, this function will look a lot more presentable.

function getCheckedList(source, destination) {
  for (let i = 0; i < source.length; i++) {
    if (source[i].checked) destination.push(source[i])
  }
}
Copy the code

Or take the following example:

  • name & nameString
  • User & UserObject
  • getAccount() & getAccounts() & getAccountInfo()

This kind of meaningless distinction, others do not know what the specific distinction is, when to use what, so the naming of the distinction, to the reader can identify the difference in the way to distinguish.

Use the read name

Not much, but examples:

function genymdhms(){}
function modymdhms(){}
Copy the code

In this case, you can only hope that the function logic is clear. You can read the function logic to understand the function function, but this is obviously not correct, and if you change the name to the following, it will be much clearer.

function generationTimestamp(){}
function modificationTimestamp(){}
Copy the code

Use searchable names

Now editor provides many functions, we can easily search specified name, you can also batch replacement, but if a variable name is e, m, name it, we have such a powerful editor empty, still they are helpless, because may be dozens or even hundreds of variables with the same name, and so the name should be able to say its specific meaning, Usually this name, also easy to search. Of course, short names can speed up our coding and reduce code commits, but the length of the name should correspond to its scope size. It is fine to define I as the index of a loop; When working with linked lists or arrays, it’s ok to call a double pointer pre and next.

Valid prefix

When we define a function name that has an action, we add the prefix of the corresponding action to make the function name express its intention more clearly. For example:

function getName(){}
function setAge(){}
function isChecked(){}
Copy the code

For example, we can prefix all interface methods with API, which makes it easy to distinguish normal functions from interface functions.

No puns

We want to avoid the use of the same word for different purposes, the same term for different concepts, is a pun. For example, there is a method add that sums the parameters of type Number passed in. If you need a method to insert an item that meets the criteria into the list, you should not use Add. You would be better off using insert or Append.

Use names that are close to the business

If you can’t name your work in terms familiar to programmers, use business-friendly names, because often the programmer who maintains the code knows the business, even if he doesn’t know what it means, and can consult product managers and business people. If we had named it any other way, it would have been much harder for him to read our code.

The above is about naming sharing, take every naming seriously! 😊