Inscription: the book has its own house of gold, the book has a face like jade. It’s like one piece, waiting for us to discover, to find. Not every place has a One piece. Maybe somewhere, there is a thought-provoking phrase waiting to be discovered. Some may have missed it, some may have found it, and that may be the charm of reading.

Written in the book of the former

I read a lot of technical books, this “Code” is worth me to write a summary of it, this is the first book I wrote in Nuggets after reading, I strongly advocate reading books.

Because, personally, I think every book, in the process of writing a book, have invested a lot of time and effort, they will be as much as possible to gain experience, summed up in a comprehensible way as possible in the book, this is an instinctive behavior, as if to achieve a successful career in the game, a good book, You can say that is the original intention of every book publisher.

So I give a thumbs up to anyone who has published a book. Maybe there are a lot of things in the book that we think are copied or not nutritious. But in my experience, if you read a good book, it’s almost always a chapter, or even a paragraph, that gives you a sense of revelation or surprise. It’s like the indescribable surprise and joy of playing king of Punches when you suddenly make a big move… MMM ~~(never pressed out)&¥&¥#…

Start my show

Just enough, I’m ready to get back on track. Code daquan this book, I bought a long time ago, then not into the circle 😂, read a part of it, also made some notes, write in the small book, since the circle, did not read, in recent days, the identity of the former end engineer to complete again, found a new continent, found several one piece. I can no longer agree with the idea of rethinking the past and learning the new, so I would like to share some of my conclusions and findings, as one of the book’s accolades says:

Every programmer should read this excellent book.

Let’s get started…

“Code” a total of 944 pages of content, very realistic, which involves a lot of knowledge, the main code is Java and C++ based. It’s not the form of the code that matters, it’s the idea that matters. Here are a few things I’ve learned for front end engineers to get started.

The conditional switch statement is used correctly

Most of the time, when we use the switch statement, we do not have a clear principle on how to use default, sometimes under default, nothing will be executed, sometimes under default, the last possibility will be executed. And sometimes there are so many cases that we don’t really care about sorting. And so on and so forth, in fact, this is a bad behavior in programming. So, what is the correct posture for writing switch statements? See below:

Tip1 — Let Default do its job

In principle, do not write the last possibility under default, because default is designed to catch errors. Therefore, all cases in the business should be captured by case, which also reflects the function of using the label after the case to indicate what kind of case it is. However, the label cannot be added after default, so the description of possible situations is lost. For example, in the front end, if the status code returned by the request is judged, it can be written as follows:

switch(code) {
  case: '1':
    console.log('success')
    break
  case: '0':
    console.log('failure')
    break
  default:
    dealError()
}
Copy the code

As can be seen from the above code, default does not do any operations with normal cases. It is specially used to detect and process errors. Of course, if some cases are regarded as errors in business, default can also be written uniformly.

Tip2 – Make case simple, orderly and efficient

1: If there are many cases, they should be arranged from top to bottom according to the frequency of occurrence, so that the overall efficiency of switch statement code will be improved.

2: If a case, too many statements, then decisively encapsulated subroutines to call. Avoid writing too many statements in a case that make it difficult to understand.

How do YOU determine the complexity of your code

We may instinctively think of big O method what, for the front end, big O that kind of mode is not suitable, big O is to measure the complexity of the algorithm. An interesting way to determine complexity is mentioned in The total, called the Tom McCabe method, which simply measures complexity by counting the number of decision points in a function. Here is one way to calculate decision points (combined with the front end) :

  1. from1You start by going all the way down through the function
  2. Once meetif while for elseOr higher-order functions with loops, likeforEach mapSuch as it is1
  3. Add to each case in the case statement1

For example:

function fun(arr, n) {
  let len = arr.length
  for (let i = 0; i < len; i++) {
    if (arr[i] == n) {
        // todo...
    } else {
        // todo...}}}Copy the code

Using Tom McCabe’s method to calculate complexity, the number of decision points for fun is 3. Once you know the number of decision points, how do you know what the measure is? Here is a numerical interval judgment:

The number interval The measurements
0 to 5 This might be a good function
6-10 I have to find a way to simplify this function
10 + Split part of this function into another function and call it

As you can see from the criteria above, the code I wrote above, with a number of 3, is a pretty good function. Personally, I think this judgment method is very scientific and simple, which can be used as a consideration point to determine whether a function needs to be reconstructed when writing code. After all, when a function is scanned, the number of decision points can be roughly known, which is easy to calculate.

What do you think of abstraction and encapsulation and modules?

Well, sometimes, just because we don’t know doesn’t mean we can’t. A lot of times it’s like, I’ve really read about this or I’ve really researched this and I’ve forgotten 😂. So now, when you see this place, just like it (hee hee).

I think this kind of partial concept of things, everyone can answer differently, but as long as you really understand the essence of it or a kind of answer, in fact, it is enough. Let me give you my own thoughts on abstraction and encapsulation and modules.

In my eyes, abstraction is actually to turn chaos into order and scattered into a whole. We often talk about abstracting business code into components, making it componentized. In fact, it is the process of turning scattered parts into wholes and chaos into order. Take a lychee:

For example, our project has not done the componentization, popover this function, or various pages to write their own popover code. Now we need to refactor this fragmented and chaotic popover into an overall ordered popover component. So, let’s look at the original popover code and find the following problems:

  1. Code is repetitive and scattered across pages.
  2. Code chaos, no unified entry, no unified display logic.

So how do you solve that? Well, that’s when you need to abstract the popover, and one way to do that, is to get rid of repetition and clutter, and if you get rid of that, that means that the abstraction is working.

I’m going to mention ADT, which is the basis for classes in object oriented programming, called Abstract Data Type, or Abstract Data Type, but I don’t want to use that, I’m going to use DOM BOM, I’m going to call it ADM. Abstract Data Model is an Abstract Data Model. I don’t know if I can play like this, but I think it’s ok, hee hee. No problem. I’ll move on from here.

We need to collect all the data that we can use for popover, and then put that data into an object model, which I’ll call a popover man, for the sake of metaphor, who has life. So the popover guy’s entity is made up of this data, OK, so it’s going to aggregate all of the data that was scattered before into one entity, which is the whole thing. Look at the following sentence:

Without encapsulation, abstractions are often easy to break.

If I just abstract, if I make the scattered whole, but I don’t make the chaotic orderly, then the abstraction will be broken, just like the popover guy has the data, and I’ll use a fancy metaphor here. Let’s say the popover guy has a million, the key million is still public, and it’s a tragedy.

A lot of people want to borrow money from him, if the popover guy doesn’t specify how to borrow money beforehand. Then it will be very exciting, friend A wechat asked him to borrow money, friend B Alipay to his collection, social bandits directly threatened to borrow money from him, more awesome, directly forced to kidnap him, and then wait on the sword. Popover people in the heart bitter ah, uncomfortable.

Finally pop window person enlightenment, beforehand specified the way to borrow money, can only first through SMS, other ways of borrowing money will be refused, and through his consent, at the same time resolutely not open their property. From then on, no one knew how much money the popup person had, and they thought they were poor (the popup person was a programmer). Even if they wanted to borrow money, they could only tell the popup person by text message how much money they wanted to borrow, and then lend it to you after agreeing. From then on, popover lived a happy life.

It’s an improvised chestnut. I realized I had a pretty good imagination. Give yourself 0110, 0110, 0110, in fact, you probably know what I want to express after reading. This is the purpose of encapsulation, not only for the front-end domain, but for all object facing domains. If there are exceptions, cover your mouth, no.

As we can see from the above, abstraction and encapsulation are inextricably linked. Take a closer look at the above story and you’ll see that in making chaos orderly, we’re actually making accessibility as low as possible, the principle of encapsulation itself:

The principle of encapsulation is to keep accessibility as low as possible.

Many people know that encapsulation is about reducing accessibility, but don’t know why, and probably do? I’m going to interrupt here for a little bit.

There is a very funny phenomenon in the expensive (programmer) circle, that is, I know the purpose of a knowledge, but I can not tell the principle, or I have checked, trying to understand this principle, but there will always be a hazy sense of ignorance around their own. Then ob in the mind: so first, the back say 😂. And then you don’t understand it very well. How do I know this? Because I feel this way sometimes, and feelings can’t be avoided. What can be done is not to forget to solve the hazy confusion at that time in the future.

The interruption ends and continues with 🙂, how much money I have you cannot know, if you know, my money will become unsafe. You can only access me through fixed channels, and you cannot directly access the data. Only with my consent can you proceed with relevant operations. Accessibility is explained pretty well. Okay, I won’t explain.


So what is the concept of front-end modularity?

In fact, it can be understood as componentization. Modularity, as the name implies, wants to express the consciousness of wanting the whole. Since the whole, it needs to be encapsulated. Before encapsulation, it needs to be abstract, and then return to the essence. So how is the front end modular today?

JavaScript is an object-oriented programming language, and at least one of the things that can be said about JavaScript is that everything in JavaScript is an object, so to speak, but one of the awkward things about JavaScript is that there are no classes, and while there are classes, they’re just syntactic sugar. TypeScript is not considered here. So how does it achieve modularity?

Implement an abstract model of a class in a programming language, known as ADM. In my opinion, front-end modularity without the sugar of class syntax is achieved by using JavaScript’s private variable and closure features. In ES5, JS has no block-level scope, only global variables and private variables. If there is no private variable, then JavaScrript is GG. Therefore, I am curious about the original JS design, which adopts the c-like language design style, why did not implement block-level scope? Feel JS not to need so muti_function at that time 😂. If there are private variables, then there are private properties and private methods, which are essentially variables. I will not paste the specific code, write a pseudo-code:

function fun() {v1 is a private property and f1 is a private method// Return an object
    return{v2 is a common attribute and f2 is a common method {common methods can access and modify private attributes and private methods v1 handle f1}}Copy the code

How to write high-quality functions

How to write high quality subroutines, JS functions are subroutines (99% correct). Some of the high quality summaries in the whole system are not applicable to JS. Here I combine some of my own experience and summary. Read on:

Ever wonder why functions were invented?

As a front end engineer, I pay attention to this problem. Tilt your head 45 degrees, think about it in your head for 10 seconds, maybe blink a few times, don’t ask me why I know your state, because XX. In fact, everyone can say some of their own opinions, do not need an answer, but I still want to give a seemingly demanding high answer. That is:

Functions are by far the most important means invented to save space and improve performance. Notice, there’s no one. So what we know for sure is that it’s used to save space and improve performance. In this case, if we do not optimize the function, write a high-quality function, does not lose its existence significance. Now the most critical question is: how to optimize the function, write the function of high quality?

if (str === 'hello world') {
    console.log('hello world')}else {
    console.log('666')}Copy the code

Print (STR); print(STR); print(STR); print(STR); print(STR); print(STR)

How to write high-quality functions. In fact, this point can write an article, here I do not elaborate on the elaboration, just mention a few points, high quality concrete implementation again after 😂.

Starting with a baby, it’s important to have a good name

Cannot output on the starting line, consider the following points:

  1. The name should clearly describe the purpose of the function
  2. Unify good writing form. For example, the use of underline, hump and other naming forms
  3. Agree on the word form, noun + verb, or verb + noun

Gracefully pass and handle parameters

  1. The parameter object mode can be used when there are many parameters
  2. Parameters are not fixed, such as dynamic parameters, can be usedES6The extension of the operator
  3. useES6To deal with the problem of parameter default values

Some considerations when designing functions

  1. Avoid function code duplication
  2. Reduce the function code size
  3. Increase function robustness
  4. Comment style should be consistent
  5. Keep as much as possiblepureProperties, that is, idempotent, so that it can maximize the prevention of late all kinds of puzzlingbug

About span and survival time

Variables have a property of their own, called lifetime, and in programming languages, the lifetime of variables should be as short as possible. In this case, if we look at global variables in terms of span and lifetime, we will see why we should avoid using global variables, which have long span and lifetime.

Eggs: JS should avoid global variables, in fact, one of the main reasons is that JS code execution is from inside out, if it is a global variable, then the search time is relatively long, so in JQuery and other source code, directly pass window as a parameter to the function, it has its reason, can improve the code performance.

A little-known point about Boolean expressions

Look at the following code

let i = true 
if (i = true) {
  // todo...
}
Copy the code

As you can see, if you accidentally drop the = sign in your business code, it will not report an error, but if you write it like this:

let i = true
if (true = i) {
  // todo...
}
Copy the code

The interpreter will report an error if the left side of the expression is not a variable. So in JS programming, you can put constants to the left of the equals sign. This is a very small tip, and on the front end, adding an ESLint to your project can completely avoid this error. If you don’t write ESLint, consider this tip, and if you use code checker, it’s a good idea.

A little buddhist knowledge

How to fix bugs and code defects

Well… Colorful face? Git saves source code in a timely manner.

  1. Relax: HMM…
  2. Make sure you have a good reason to change your code. The reason should be sufficient and well-founded.
  3. Make one change at a time

note

  1. Design patterns this will not be summarized, there are many things, need to be taken out separately.
  2. Some system-level summaries will also be left out, not related to the front end.
  3. Never mind recursion, because you don’t use recursion much in the front end.
  4. Pseudo – code programming is covered separately
  5. For writing high-quality functions, it’s easy to summarize, because there are a lot of things involved, but HERE I would like to mention some essential knowledge, such as the purpose of the creation, sometimes you write a lot of functions, do not think about the problem, now you see the heart of a feeling of clarity.

Lovely disclaimer at the end: If retweeted or quoted, please post the original link. This article is just like a book, there may be some places for you is not nutrition, but as long as there is a paragraph, or a sentence let you feel surprised, I am very happy. This article may have some mistakes, welcome comments pointed out, also welcome to discuss. Please forgive me if the article may not be good enough. A little more contribution, more a separate heart ~