当前位置:网站首页>[God level operation] analyze the Ninja code with the traditional Chinese thoughts of Confucius and Laozi!

[God level operation] analyze the Ninja code with the traditional Chinese thoughts of Confucius and Laozi!

2020-11-09 17:20:00 C language programming learning base

Ninja code

Learning without thinking is useless , thought without learning is perilous .—— Confucius

Ninja programmers used to use these techniques , Sharpen the mind of code maintainers .

Code review masters look for them in test tasks .

Some new developers can sometimes use them better than Ninja programmers .

Read this article carefully , Find out who you are —— A ninja 、 A novice 、 Or a code reviewer ?

Be careful : Irony detected

Many people try to follow in the footsteps of ninjas . Only a very few succeeded in .

 

Simplicity is the soul of wisdom

Write the code as short as possible . Show how smart you are .

In programming , Use more clever programming language features .

for example , Take a look at this ternary operator  '?':

// From a famous JavaScript Code intercepted in the library

i = i ? i < 0 ? Math.max(0, len + i) : i : 0;

cool , Am I right? ? If you write like this , Those who see this line of code and try to understand  i  What is the value of developers , There will be one “ Happy ” Time . Then I'll come to you to find out .

It's always better to tell him that it's shorter . Guide him into the path of Ninja .

 

A variable of letters

Tao Yin is nameless . The only way I can do it is to be good at lending .—— Lao tze ( Moral by )

Another way to speed up programming is , Use single letter variable names everywhere . for example  a、b  or  c.

Short variables are like real ninjas in the forest , I can't find it in a moment . No one can get through the editor “ Search for ” Function to find it . Even if someone does , He can't either “ Decipher ” Give variable name  a  or  b  What does it mean .

…… But there is an exception . A real ninja would never be in  "for"  Use in loop  i  As a counter . It can be anywhere , But it won't work here . You can look for , You can find a lot of unusual letters . for example  x  or  y.

How cool it is to use an unusual variable , Especially in the long 1-2 page ( If you can , You can write longer ) When used in the circulatory body of . If someone wants to study the inner implementation of the loop , It's hard for him to find variables very quickly  x  It's actually a cycle counter .

 

Using abbreviations

If the team rules prohibit the use of a letter and fuzzy naming — Then shorten the naming , Use abbreviations .

like this :

    * list -> lst

    * userAgent -> ua

    * browser -> brsr

    * …… etc.

Only people with really good intuition , To understand such naming . Shorten everything as much as possible . Only people who are really valuable , To maintain the development of this code .

 

Soar high, Abstraction .

There is no corner ,

Was a late bloomer ,

Great sound is hard to hear ,

The great form has no shape .

—— Lao tze ( Moral by )

When choosing a name , Try to use the most abstract words . for example  obj、data、value、item  and  elem etc. .

*  The ideal name for a variable is  data.  Use it wherever you can . You bet , Every variable holds   data (data), Right ?

    …… however  data  What to do if it has been used ? You can try it  value, It's also very common . After all , A variable always has a   value (value), Right ?

*  Name the variable according to its type :str、num……

     Give it a try . Novices may be surprised — Are these names really useful for ninjas ? in fact , Helpful !

     One side , Variable names still have some meaning . It shows what's inside the variable : A string 、 A number or something . But when an outsider tries to understand the code , He will be surprised to find that there is actually no valid information ! In the end, you can't change the code you think about .

     We can debug through code , It's easy to see the type of value . But the meaning of variable names ? Which string or number does it store ?

     If the depth of thinking is not enough , There is no way to understand .

* …… But if we can't find more of them ?  You can add a number :data1, item2, elem5……

 

Pay attention to the test

Only a really careful programmer can understand your code . But how to test ?

One way —— Use similar variable names , image  date  and  data.

Mix them as much as you can .

It's impossible to read this code quickly . And if there's a typo …… forehead …… We've been stuck here for a long time , It's time for dinner (⊙v⊙)

 

Synonyms for intelligence

The hardest thing is to find a black cat in a dark room , Especially if there is no cat .—— Confucius

Yes   The same   Use of things   similar   The name of , 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…  start , for example  displayMessage. If another function shows something else , For example, a user name , The name can be  show…  Start ( for example  showName).

It suggests that there are subtle differences between these functions , There is no such thing as .

Make an agreement with the other ninjas in the team : If Zhang San is in his code with  display...  Let's start with a “ Show ” function , Then Li Si can use  render.., Wang Er can use  paint.... You can see how interesting and diverse the code has become .

…… Now it's a hat trick !

For two functions with very important differences — Use the same prefix .

for example ,printPage(page)  Function will use a printer (printer).printText(text)  Function to display text on the screen .

Let an unfamiliar reader think about :“ The name is  printMessage(message)  Where will the message be placed by the ? Printer or on screen ?”.

To make the code really stand out ,printMessage(message)  The message should be output to a new window !

 

Reuse names

The beginning is famous ,

There is also a name ,

I will also know ,

It's not dangerous to know .

—— Lao tze ( Moral by )

Add new variables only if absolutely necessary .

otherwise , Reuse existing names . Just write the new value into the variable .

In a function , Try using only variables passed as parameters .

So it's hard 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 people reading code . A less intuitive person has to analyze the code line by line , Track changes in each code branch .

An advanced scheme of this method is , Secretly replace its value in a loop or function .

for example :

function ninjaFunction(elem) {

  // Based on variables elem Carrying out the work 20 Line code

  elem = clone(elem);

  // also 20 Line code , Now we use clone After elem Variable .

}

Want to use in the second half  elem  The programmers of will be surprised …… Only during commissioning , After checking the code , He'll find out that he's using cloned variables !

I often see code like this , Even for experienced ninjas, it's deadly .

 

The fun of underline

Underline the variable name  _  and  __. for example  _name  and  __value. If only you know what they mean , That would be great . perhaps , Add these underscores just for fun , It doesn't mean anything , That would be even better !

Underline is a double shot . First , The code gets longer , Less readable ; also , Your developer partners can take a long time , To find out what underlining means .

Smart ninjas use underscores in one place of the code , Then deliberately avoid using them in other places . This makes the code more vulnerable , And improve the possibility of future errors in the code .

 

Show your love

Show us your rich feelings ! image  superElement、megaFrame  and  niceItem  Such a name must inspire the reader .

in fact , On the one hand , Seems to have written something :super..、mega..、nice... But on the other hand — No details were provided . People who read the code can spend an hour or two on paid work , Think hard to find a hidden meaning .

 

Overlapping external variables

He who deals with the light does not see a thing in the dark ,

Those in the dark can see the central area .

—— Guan Yinzi

For variables inside and outside functions , Use the same name . It's simple , Don't bother to think about a new name .

let user = authenticateUser();

function render() {

  let user = anotherValue();

  ...

  ... Many lines of code ...

  ...

  ... // <-- A programmer wants to use user Variable ……

  ...

}

Research on  render  Programmers of internal code may not notice , There's an internal variable  user  Shielding the outside  user Variable .

Then he would assume that  user  It's still an external variable and use it ,authenticateUser()  Result …… The trap is coming out ! How are you? , The debugger ……

 

Side effects everywhere !

Some functions don't seem to change anything . for example  isReady(),checkPermission(),findTags()…… They are assumed to be used to perform calculations 、 Find and return data , They don't change any data outside of themselves . This is known as “ No side effect ”.

A very surprising technique is , Apart from the main task , Add a... To them “ Helpful ” action .

When your colleagues see it named  is..、check..  or  find...  When a function of a changes something , There must be a look of stupidity on his face — This will widen your rational boundaries .

Another way to surprise is , Return non-standard results .

Show your original ideas ! Let call  checkPermission  The return value of is not  true/false, It's a complex object that contains the results of the check .

Those who try to write  if (checkPermission(..))  The developer of the , I wonder why it can't work . Tell them :“ Read the document ”. Then give this article .

 

Powerful functions !

The road is wide ,

It can be left or right .

—— Lao tze ( Moral by )

Don't restrict functions to what is written in the name . Broaden a little .

for example , function  validateEmail(email)  Sure ( In addition to checking the correctness of the email ) Display an error message and ask to retype the message .

Extra actions should not be obvious in function names . A real ninja would make them invisible in the code .

Combine multiple actions , Protect your code from reuse .

Imagine , Another developer just wants to check the mailbox and not output any information . Your function  validateEmail(email)  It's not suitable for him . So he won't interrupt your thinking by asking you anything about these functions .

 

summary

All of the above “ Suggest ” It's all extracted from real code …… occasionally , The code is written by experienced developers . Maybe more experienced than you ;)

    * Follow one of them , Your code will be full of surprises .

    *  Follow a large part of it , Your code will really become your code , No one will want to change it .

    *  Obey all , Your code will be a valuable example for young developers looking for inspiration .


 

Whether you change careers or not , It's better to be a beginner , It's OK to be advanced ——【 It's worth clicking into 】 Programming learning club for programmers

involves :C Language 、C++、windows Programming 、 Network programming 、QT Interface development 、Linux Programming 、 Game programming 、 Hackers and so on ......


 

An active 、 High profile 、 High level programmer programming learning Hall ; Introduction to programming is just by-pass , Only the improvement of thinking is valuable !

 

版权声明
本文为[C language programming learning base]所创,转载请带上原文链接,感谢