Ninja code
Learning without thought is labor lost; thought without learning is perilous.
– Confucius
Past programmer ninjas used these techniques to sharpen the minds of code maintainers.
Code review masters look for them in test tasks.
Novice developers can sometimes even use them better than ninja programmers.
Read this article carefully and find out who you are — a ninja, a novice, or a code reviewer?
Note: Irony is detected
Many tried to follow in the footsteps of the ninjas. Very few have succeeded.
Brevity is the soul of wit
Write the code as short as possible. Show me how smart you are.
In programming, use some clever programming language features.
For example, look at the ternary operator ‘? ‘:
// Code from a well-known JavaScript library
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
Copy the code
Cool, right? If you do, developers who look at this line of code and try to understand what the value of I is will have a “happy” time. And then they’ll come to you for answers.
Tell him shorter is always better. Lead him to the path of the ninja.
One letter variable
The way is unknown. Only good loans and become.
— Lao Tzu (Tao Te Ching)
Another way to speed up programming is to use single-letter variable names everywhere. For example a, B or C.
Short variables, like true ninjas in the forest, are easily lost. No one can find it through the editor’s “search” function. Even if someone did, they wouldn’t be able to decipher what the variable names A or B really meant.
… But there is one exception. A true ninja would never use I as a counter in a “for” loop. It works anywhere, but it doesn’t work here. If you look anywhere, you’ll find a lot of unusual letters. Let’s say x or y.
How cool it is to use an unusual variable, especially in the body of a loop that is 1-2 pages long (or longer if you can). If one were to study the inner implementation of a loop, it would be difficult to quickly figure out that the variable x is actually a loop counter.
Use abbreviations
If team rules forbid using one letter and ambiguous names — shorten the name and use abbreviations instead.
Like this:
list
->lst
userAgent
->ua
browser
->brsr
- … Etc.
Only people with really good intuition can understand such naming. Shorten everything as much as possible. Only truly valuable people can maintain the development of such code.
Soar high, abstract.
Generous no corner, late bloomer, big sound xi sound, invisible elephant.
— Lao Tzu (Tao Te Ching)
When choosing a name, try to use the most abstract word possible. Examples include obj, data, value, item, and ELEm.
-
An ideal name for a variable is data. Use it wherever you can. Indeed, each variable holds data, right?
… But what if data has already been used? You can try value, which is also very common. After all, a variable always has a value, right?
-
Name a variable according to its type:
str
,num
…Give it a try. Newbies may wonder – do these names really work for ninjas? In fact, it works!
On the one hand, variable names still have some meaning. It tells you what’s inside the variable: a string, a number, or something else. But when an outsider tries to understand the code, he is surprised to find that there is actually no valid information! In the end, you can’t change the code you’ve thought about.
We can easily see the value type through code debugging. But what about variable names? Which string or number does it store?
If you don’t think deeply enough, you can’t figure it out.
-
… But what if you can’t find more? You can add a number: data1, item2, elem5…
Pay attention to the test
Only a really careful programmer can understand your code. But how do you test it?
One way — use similar variable names, likedate
和 data
.
Mix them as much as you can.
It’s impossible to read this code quickly. And if there’s a typo… The forehead… We’ve been stuck here for a long time. It’s time for dinner.
Intelligent synonyms
The hardest thing is to find a black cat in a dark room, especially if there are no cats.
– Confucius
Using similar names for the same things can make life more interesting and show your creativity.
For example, function prefixes. If a function’s function is to display a message on the screen — the name can be display… Beginning, for example, displayMessage. If another function shows something else, such as a user name, the name can start with show… Start (for example, showName).
There are subtle differences between these functions, but there aren’t.
Make a deal with the other ninjas on the team: if Zhang SAN uses display in his code… To start a “display” function, then We can use render.. Wang 2 can use paint… . You can see how interesting and varied the code has become.
… Now it’s a hat trick!
For two functions with very important differences – use the same prefix.
For example, the printPage(page) function uses a printer. The printText(text) function displays the text to the screen. Let an unfamiliar reader think: “Where does a function named printMessage(message) put the message? On the printer or on the screen?” . For the code to really shine, printMessage(message) should print the message to a new window!
To reuse the name
When a name is created, the name is also present, and the husband will know the end.
— Lao Tzu (Tao Te Ching)
Add new variables only when absolutely necessary.
Otherwise, the existing name is reused. Just write the new value into the variable.
In a function, try to use only variables passed as arguments.
So it’s hard to figure out what the value of this variable is now. I don’t know where it came from. The goal is to improve the intuition and memory of those who read the code. A less intuitive person would have to analyze the code line by line, tracking changes in each branch of the code.
An advanced approach to this method is to secretly replace its value in a loop or function.
Such as:
function ninjaFunction(elem) {
// 20 lines of code to work based on the variable elem
elem = clone(elem);
// Another 20 lines of code, now use the elem variable after clone.
}
Copy the code
Programmers who want to use ELEM in the latter half will be surprised… It is only during debugging, after examining the code, that he discovers he is using the cloned variable!
Code like this is often seen and can be deadly even to an experienced ninja.
The fun of underlining
Precede the variable name with the underscores _ and __. For example, _name and __value. It’s great if you’re the only one who knows what they mean. Or underline them just for fun, without meaning anything, which is even better!
Underlining kills two birds with one stone. First, the code becomes longer and less readable. Also, your fellow developers will probably spend a lot of time figuring out what underline means.
A smart ninja would use underscores in one part of the code, and then deliberately avoid them elsewhere. This makes the code more vulnerable and increases the likelihood of future errors.
Show your love
Show us all your emotions! Names like superElement, megaFrame, and niceItem are sure to inspire readers.
In fact, from one point of view, it seems to have written something: Super.. , mega.. And nice.. . But on the other hand — didn’t provide any details. The person reading the code might spend an hour or two of paid work trying to find a hidden meaning.
Overlapping external variable
He who sees can not see what is in darkness; he who sees what is in darkness can see what is in light.
– GuanYinZi
Use the same name for variables inside and outside the function. It’s easy. Don’t bother thinking of a new name.
let user = authenticateUser();
function render() {
letuser = anotherValue(); . . Many lines of code... . .// <-- some programmer wants to use the user variable here.... }Copy the code
Programmers looking at render’s internal code may not notice that there is an internal variable user that masks the external user variable.
Then he’ll assume that user is still an external variable and use it, the result of authenticateUser()… The trap is out! Hello debugger…
Side effects everywhere!
Some functions look like they don’t change anything. Examples are isReady(), checkPermission(), findTags()… They are assumed to be used to perform calculations, find and return data without changing any data outside of themselves. This is called “no side effects”.
A surprising trick is to add a “useful” action to them in addition to the main task.
When your colleagues see names named is.. And check.. Or find… When a function of delta of delta changes something, there will be a blank look on his face — which will stretch the boundaries of your rationality.
Another way to surprise is to return nonstandard results.
Show your original idea! Let the return value of the call to checkPermission not be true/false, but a complex object containing the result of the check.
Those who try to write if (checkPermission(..) ) and wonder why it doesn’t work. Tell them, “Go read the document.” Then give the article.
Powerful function!
The road is broad, its left can be right.
— Lao Tzu (Tao Te Ching)
Don’t let a function be limited by what’s in its name. Widen it.
For example, the function validateEmail(email) can (in addition to checking the correctness of the message) display an error message and ask for re-entry of the message.
Additional actions should not be obvious in the function name. A true ninja would make them invisible in the code.
By combining multiple actions, you can protect your code from being reused.
Imagine another developer who just wants to check the mailbox and doesn’t want to output anything. Your function validateEmail(email) is not appropriate for him. So he’s not going to interrupt your thinking by asking you anything about these functions.
conclusion
All of the “advice” above is distilled from real code… Sometimes, this code is written by experienced developers. Maybe more experienced than you;)
- Follow one of these, and your code will be full of surprises.
- Follow a big part of it, and your code will really be your code, and no one will ever want to change it.
- Follow all, and your code will be a valuable example for young developers looking for inspiration.
This article was first published on the wechat official account “Technology Talk”. Welcome to search and subscribe for more exciting content on wechat.
Modern JavaScript Tutorial: open source modern JavaScript from the beginning to the advanced quality of the tutorial. The React official documentation recommends a JavaScript tutorial alongside MDN.
Read online for free: zh.javascript.info
Scan the qr code below to follow the wechat official account “Technology Talk” and subscribe for more exciting content.