From the perspective of the machine's point of view, variables, functions, classes ...... name is used to distinguish other things.
From the human perspective, the difference between other things, just to name the most basic requirements, but also to help the reader understand the name of the code.
In order to give readers a better understanding of the code, named when the following two points to note:
- The avoidance of doubt - let the reader understand correctly
- Explain what, not how - to improve the reader's understanding of efficiency
1. Avoid ambiguity
const limitOfLoginTries = 5;
This variable is used to define: how many times the wrong password is entered, the user will be locked.
In the end it will be locked or 4 times wrong wrong five locks?
limit
There is ambiguity on the question of whether the inclusive values. Here with max
better.
const getPath = (start, end) => {
// expensive calculation
......
}
The method of the path between the starting and ending points for calculation.
get
Common to operation from map
taking an element.
Subconscious will think it is a lightweight action.
However, an example method will perform complex calculations. The method is easy to be taken lightly caller, called repeatedly, eventually leading to performance problems.
Here with caculate
better.
These two examples from the "write-readable code Art" this book.
2. Description what rather than how
const moneyMultiplyRatio = money * 0.027;
Money is multiplied by a percentage of the same name and the code says.
After reading still do not know why this variable would like.
If the interest is, then, with interest
much better.
The intention expressed by the variable variable names.
A name to a piece of code, the intent of the code expression is function
.
The refrigerator loaded elephant, reading comprehension 3 行名字
is clearly better than 100 行实现细节
more efficient.
refrigerator.open();
refrigerator.put(elephant);
refrigerator.close();
This is consistent and functional programming declarative ideas.
Note To do -what, hiding technical details -how.
Written by people thinking more clearly, people understand more easily read.