This article for hungry people valley lecturer fangfang original article, first in the front of the learning guide.

The following is my “JS simple” the 6th lesson of the handout, if it is helpful to you just like it

This lesson is on “How to improve code readability”, which is not related to the previous part, but a general technique for writing code.

Note that we’re not talking about “how to improve the performance of your code.”

Code optimization fundamentals

  1. Legibility is preferred
  2. If it’s not a performance bottleneck, don’t rewrite code for performance
  3. Conservation of Complexity principle: No matter how you write code, complexity is a corollary: If the logic is complex, the code should look complex. If the logic is simple, the code should look simple.

named

Three big problems for programmers

  1. Variable naming
  2. Cache invalidation
  3. Loop boundaries show the importance of variable naming.

There are a lot of naming conventions on the web that you can refer to. This lesson is just about the basics.

1. Pay attention to the parts of speech

  • Use “nouns” for common variables/attributes
var person = {
      name: 'Frank'
  }
  var student = {
      grade: 3,
      class: 2
  }
Copy the code
  • Bool variable/attribute use “adjective” or “be verb” or “modal verb” or “hasX”
var person = {
      dead: false// If it is an adjective, there is no need to add is before it.true// The modal verbs can, should, will, need, etc.true// Be followed by the noun hasChildren:true, // has + noun}Copy the code
  • Normal functions/methods start with a verb
var person = {
      run(){}, // intransitive verbsdrinkWater(){}, // transitive verb eat(foo){}, // transitive verb with parameter (parameter is noun)}Copy the code
  • Callbacks, hook functions begin with a preposition, or use the present perfect tense of a verb
var person = {
      beforeDie() {},afterDie() {}, / / orwillDie() {}deadAfterDie} button.adDeventListener (){// Bool dead (){// Bool dead (){// Bool dead (){// Bool dead ();'click', onButtonClick)
  var component = {
      beforeCreate() {},created() {},beforeMount() {},mounted() {},beforeUpdate() {},updated() {},activated() {},deactivated() {},beforeDestroy() {},destroyed() {},errorCaptured(){}
  }
Copy the code
  • Add prefixes to confusing places
div1.classList.add('active'// DOM object div2.addClass('active'// How about domDiv1 or eldiv1.classlist.add ()'active')
  $div2.addClass('active')
Copy the code

Attribute accessor functions can use nouns

$div.text() // It is$div.getText()
  $div.text('hi') // Actually it is$div.setText('hi')
Copy the code

Second, pay attention to consistency

  • Preposition consistency If you use before + after, stick with it everywhere in the code if you use before + perfect, stick with it if you change it around, it’s inconsistent, and inconsistency leads to unpredictability
  • The sequential consistency, for example, updateContainerWidth and updateHeightOfContainer, is in an awkward sequence, and also causes unpredictability
  • A consistent function name in a table must perfectly represent the function, no more or less. Such as
function getSongs() {return $.get('/songs).then((response){ div.innerText = response.songs }) }Copy the code

GetSongs does not imply that the function will update the page, but it does update the div

  • Either correct the function name
function getSongsAndUpdateDiv() {return $.get('/songs).then((response){ div.innerText = response.songs }) }Copy the code
  • Or I can write it as two functions
function getSongs() {return $.get('/songs) } function updateDiv(songs){ div.innerText = response.songs } getSongs().then((response)=>{ updateDiv(response.songs) })Copy the code
  • Time consistency It is possible for a variable to have a different meaning from its original meaning as the code changes, and you need to change the name of the variable in time. This one is the hardest to do, because it’s easier to write code than to change it. If the code is not well organized, it is very likely that it will be affected by the whole thing (global variables are hard to change, for example)

To change the code

If your code has unit tests, it’s safe to change. If there are no unit tests, the “baby steps” approach is needed.

“Baby steps” means you change a little bit at a time, and when you pass the test, change a little bit more, and test again, and change a little bit more… And so on.

So how do you modify a little bit? Refactoring is a book that covers a lot of methods, but it’s a little abstract if you have the time.

I’m going to name just two of them.

Use functions to change code

Steps:

  1. Put a bunch of code into a function
  2. Take external variables that your code depends on as parameters
  3. Take the output of the code as the return value of the function
  4. Give the function an appropriate name
  5. Call this function and pass in the arguments
  6. If there are more than 5 lines of code in this function, there is still room for optimization, go back to Step 1

Use objects to change code

If there are too many small functions after using the transform method, you can string them together using objects.

Remember when we said “this is the bridge between a function and an object”, we’re going to use this to concatenate this object with all the functions.

The final code: js.jirengu.com/mimazaboke/…

Some set routines

  1. Table driven programming (as described in the Code book) all one-to-one mapping can be done with tables
  2. Self-explanatory code (in the case of API parameters) puts what others care about prominently

Bad smell

Some of the code works, but it stinks.

What code smells bad

  1. Duplicity code
  2. Outdated comment
  3. Code that has very simple logic but looks very complex
  4. Duplicate code
  5. Similar code
  6. Code that always comes together

Broken window

The theory is that undesirable phenomena in the environment, if allowed to exist, will induce people to imitate or even exacerbate them. Take a building with a few broken Windows. If those Windows are not repaired, vandals will probably destroy more Windows. Eventually they will even break into buildings and, if they find them empty, perhaps settle there or set fire to them. One wall, if some graffiti has not been cleaned off, soon, the wall is full of messy, ugly things; A few scraps of paper on a sidewalk, and soon there will be more, and eventually people will take it for granted and throw it on the ground. This phenomenon is called the broken window effect in criminal psychology.

The programmer has to do this: every piece of code that passes through your hands is better than it was before.

Add micro signal: Xiedaimala03, code: write code

A daily question, weekly resource recommendation, wonderful blog recommendation, work, written test, interview experience exchange answers, free live class, group friends share light… Countless benefits are given away for free