preface

This article is a modern JavaScript tutorial on code quality, not limited to the JavaScript language. I read very interesting, so I reprint here, the original address. In addition, if you also learn JS, force modern JavaScript tutorial, explain in simple terms, the best JS tutorial I have ever seen.

Learning without thought is useless; thought without learning is perilous.

Confucius

The ninja programmers of the past used these techniques to sharpen the minds of code maintainers.

Code review gurus look for them in test tasks.

Novice developers can sometimes use them better than ninja programmers.

Read through this article and find out who you are — a ninja, a novice, or a code reviewer?

Irony detected

Many people tried to follow in the footsteps of ninjas. Only a few succeed.

Brevity is the soul of wit

Keep your code as short as possible. Show me how smart you are.

In programming, use more 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 are going to have a good time. And they’ll come to you for answers.

Tell him it’s always better to keep it short. Lead him into the ninja path.

One letter variable

The road hides itself. A good man is a good man.

Lao Tzu (Tao Te Ching)

Another way to cut down on code is to use single-letter variable names everywhere. Such as A, B, or C.

Like real ninjas in the forest, short variables are nowhere to be found. No one can find it through the editor’s “search” function. Even if one did, one could not “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. You can do it anywhere, but it’s not going to work here. You can find a lot of unusual letters if you look for them. For example, x or y.

It’s cool to use an unusual variable, especially if it’s in the body of a loop that’s 1-2 pages long (you can write longer if you can). If one were to study the internal implementation of a loop, it would be hard to quickly figure out that the variable X is actually a loop counter.

Use abbreviations

If team rules prohibit the use of one letter and vague naming — shorten the naming and use abbreviations.

Like this:

  • listlst
  • userAgentua
  • browserbrsr
  • … Etc.

Only people with really good intuition can understand such naming. Shorten everything as much as possible. Only truly valuable people can maintain this kind of code development.

Soar high, abstraction

Generous without corner, late, big sound, elephant invisible.

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.

  • The ideal name for a variable is data. Use it wherever you can. Indeed, every variable holds data, right?

    … But what if data has already been used? Try Value, which is also very common. After all, a variable always has a value, right?

  • Name variables according to their 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 says what’s inside a 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 no valid information at all! You end up not being able to change the code you’ve thought through.

    We can easily see the type of value through code debugging. But what about variable names? Which string or number does it store?

    If you don’t think deeply enough, there’s no way to figure it out.

  • … But what if you can’t find more of them? 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 that?

One way — use similar variable names likedatedata.

Mix it up as much as you can.

It is 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.

Synonym for intelligence

The hardest thing is finding 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 creativity.

For example, function prefixes. If the function of a function is to display a message on the screen – the name can start with display… Beginning, for example displayMessage. If another function displays something else, such as a user name, the name can start with show… Start (for example showName).

Implying that there are subtle differences between these functions, which there are not.

Make a deal with the other ninjas on the team: If Joe puts display in his code… To start a “display” function, then li Si can use the render.. You can use paint… . You can see how interesting and diverse the code becomes.

… Now a hat trick!

For two functions that have very important differences – use the same prefix.

For example, the printPage function uses a printer. The printText(text) function displays the text on the screen. Let an unfamiliar reader ponder: “Where does a function named printMessage(message) put a message? On a printer or on a screen?” . For code to really shine, printMessage(Message) should output the message to a new window!

To reuse the name

The beginning makes the name, the name also has, the husband also will know, the knowledge can not be dangerous.

Lao Tzu (Tao Te Ching)

Add new variables only when absolutely necessary.

Otherwise, reuse existing names. Just write the new value into the variable.

In a function, try to use only the variables passed as arguments.

This makes it difficult to determine 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 the person reading the code. A less intuitive person would have to analyze the code line by line, tracking changes in each code branch.

An advanced alternative to this approach is to stealthily replace its value in a loop or function.

Such as:

function ninjaFunction(elem) {
  // 20 lines of code working on the variable elem

  elem = clone(elem);

  // Another 20 lines of code, now using the post-clone elem variable.
}
Copy the code

Programmers who want to use ELEm in the second half will be surprised… Only during debugging, after checking the code, does he discover that he is using cloned variables!

Such code is often seen and can be deadly even for experienced ninjas.

The fun of underlining

Prefix variable names with underscores _ and __. For example, _name and __value. It would be great if only you knew what they meant. Or, even better, they’re underlined just for fun, with no meaning at all!

Underlining kills two birds with one stone. First, code becomes longer and less readable; Also, your fellow developers may spend a lot of time trying to figure out what underlining means.

A smart ninja would use underscores in one part of the code, then deliberately avoid them elsewhere. This makes the code more vulnerable and increases the likelihood of future errors in the code.

Show your love

Show everyone the richness of your emotions! Names like superElement, megaFrame and niceItem are sure to inspire readers.

In fact, on the one hand, it seems to write 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 their paid work time scratching their heads to find a hidden meaning.

Overlapping external variables

Where there is light, there is nothing in darkness; where there is darkness, there is 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 studying render’s internal code might not notice that an internal user variable shields the external user variable.

He then assumes that user is still an external variable and uses it, the result of authenticateUser()… The trap is out! Hello, debugger…

Side effects everywhere!

Some functions look like they don’t change anything. Examples include isReady(), checkPermission(), findTags()… They are assumed to perform calculations, find and return data without changing any data outside of themselves. This is called “no side effects”.

One surprising trick is to add a “useful” behavior to them in addition to the main task.

When your colleagues see someone named is.. And check.. Or find… When your function changes something, he will look confused – this will stretch your rational boundaries.

Another way to surprise is to return non-standard results.

Show your original idea! Make the return value of a call to checkPermission not true/false, but a complex object containing the check result.

Those who try to write if (checkPermission(..) ), wondering why it doesn’t work. Tell them, “Go read the document.” Then present this article.

Powerful function!

The broad road leads to left and right.

Lao Tzu (Tao Te Ching)

Don’t let a function be limited by what it says in its name. Broaden it.

For example, the function validateEmail(email) can (in addition to checking the correctness of the message) display an error message and ask you to re-enter the message.

The additional behavior should not be obvious in the function name. A true ninja would make them invisible in the code.

By combining multiple behaviors, you can protect your code from reuse.

Imagine another developer who just wants to check the mailbox and doesn’t want to output anything. Your validateEmail function is not suitable for him. So he won’t interrupt your thoughts by asking you anything about these functions.

conclusion

All of the above “suggestions” were distilled from real code… Sometimes this code is written by experienced developers. Probably more experienced than you;)

  • Follow a few of them, and your code will be full of surprises.
  • Follow a big chunk of it, and your code will truly be your code, and no one will ever want to change it.
  • Follow them all, and your code will be a valuable case study for young developers looking for inspiration.