A preface
When it comes to source code, four words may come to mind: I’m too hard ๐๐๐. Read the source code seems to be out of reach with us, because in daily work, we basically master in the degree of proficiency, can meet the needs of the work, even if it is to see the source code, will be rejected by the complex logic of the source code, has become a lingering shadow in our hearts. So do we really need to read the source code? From my perspective, the answer is yes, reading source code is not just about the source code, it brings some added value.
I have read a lot of source code, such as mainstream front-end frameworks vue2.0, VUe3.0, React, Node framework Express, KOA, and their derivatives ecosystem react-Router, react-Redux, DVA and so on. Is it painful to read the source code? I feel that the process is painful, but after reading, I will feel a lot of harvest, feel that the effort is worth it. So let’s talk about reading the source code.
Why read the source code?
1 For the interview
A scene of test questions?
Suppose this is an interview.
Interviewer: What about the principle of vue2.0 responsiveness?
First candidate: Object.defineProperty () interceptor property, intercepting set, get.
These answers seem hard to convince me and only prove that the interviewer has prepared for the topic.
Second candidate: on the basis of the first, tell the collection of dependent DEP objects, responsible for rendering update render Watcher, recursive response, etc., and can introduce their principle and function.
Rating: 6-7 These answers are well within the criteria, and at least address the core of vUE responsiveness, showing that the candidate has at least studied in depth.
Third candidate: on the one hand, from initializing data, to parsing the template, for dependency collection. On the other hand, the ability to change from data, notify rendering Watcher of updates, to page changes, explains the whole process.
Score: 8-10 points such answers, is very perfect, can start from the source point of view, the applicant is very in-depth principle, read the source code.
From an interview question, you can see an applicant’s understanding of the framework. Reading the source code is the best way to understand the framework from the ground up. And if you make the source code clearly. It can impress the interviewer. They can even beat up the interviewer ๐๐.
2. Clearer application framework
As you read the source code, you can understand how the bottom layer works. If you encounter a problem at work, if you read the source code, you will find a solution and the problem will be solved.
I have seen a colleague encounter such a problem before.
<el-select v-model="value" >
<el-option
v-for="(item,index) in list"
:key="index"
:value="item.value"
:label="item.label"
/>
</el-select>
Copy the code
Maybe the business scenario is more complex than that, something like this. One problem is that every time you change the list and then re-select options, you find that the bound value data has changed, but the view has not changed.
If you don’t have some knowledge of the DIff algorithm in VUE, you will be blindside to this phenomenon. Why hasn’t the view changed when the data has changed? what?
If you have read diff algorithm and the patch process of sub-nodes, you will find that this problem mainly comes from the use of index as key. In an update, although the data was changed, the wrong element node was reused according to index, resulting in the mismatch between view and data.
For frameworks or open source libraries, if we have a problem with using them, instead of raising an issue on GitHub and waiting to be solved, we can look at the source code ourselves and maybe the answer is there. Is the so-called suddenly look back, that person is in the lights dim.
Improve programming ability and expand knowledge blind spot
I personally feel that reading the source code is absolutely to improve the ability to expand the knowledge of the shortcut. Why do you say so? Let’s start with two short classic code snippets:
no 1 redux compose
export default function compose(. funcs) {
if (funcs.length === 0) {
return arg= > arg
}
if (funcs.length === 1) {
return funcs[0]}return funcs.reduce((a, b) = > (. args) = >a(b(... args))) }Copy the code
It’s a classic example of middleware on the front end, with minimal code and a stroke of genius. We can learn from the source code, the programming techniques, and even if we can’t write classical functions like this, we can figure out when to use inheritance and when to use closures.
In the process of reading the source code, there will be a lot of advanced usage and we rarely use the API, we can effectively knowledge literacy.
No2 vue3.0
Vue3.0 reactivity/SRC/reactive. Ts
const rawToReactive = new WeakMap<any, any>()
const reactiveToRaw = new WeakMap<any, any>()
const rawToReadonly = new WeakMap<any, any>()
const readonlyToRaw = new WeakMap<any, any>()
Copy the code
In VUe3.0, several WeakMaps that save dependent collection relationship have triggered my thinking about WeakMap and garbage collection mechanism. WeakMaps keeps a weak reference to the object referenced by the key name, meaning that the garbage collection mechanism does not take that reference into account. As soon as all other references to the referenced object are cleared, the garbage collection mechanism frees the memory occupied by the object. In other words, once it is no longer needed, the key name object and the corresponding key value pair in WeakMap will disappear automatically, without manually deleting the reference.
Reading source code, on the one hand, helps us write poetic code, on the other hand, expands our knowledge. Anyway, it smells good!
4. Develop the ability of design thinking and architecture
Good source code has the big picture, the thinking, and the backbone of the architecture ability, which is an advanced engineer or is planning to advance, is the most lacking.
You might cram like crazy, read like crazy on this blog, or work like crazy on programming problems, but when you take on a big engineering project, you still don’t know what to do and end up in a mess. Why is that? Maybe there is a lack of design thinking and architectural skills.
The three realms of life and the three realms of reading source code are the same. Slowly their programming ability will be affected by subtle.
When you first start looking at source code, look at your own code or your own code. But slowly, you will find yourself writing code, under the influence of the source code, is not like the appearance of my original, day after day, when you insist, you will understand source real architecture design, architecture, and be able to own design code of their soul, you will find your own code or your own code, the reason is that their progress, The ability to control the situation.
How to read the source code
The benefits of reading source code are described above, so let’s talk about how to read source code effectively.
One breaks the whole into parts
Rome was not built in a day, reading the source code is not a matter of a day, we have a plan to read the source code. Set aside time to read a little bit every day, and then focus on taking notes, can be MD, can be handwritten notes, in short, to record the core content, because first, a good memory is better than bad writing, can deepen our impression. Second, before each reading, take out the notes of the last time to see, to achieve perfect cohesion. The entire source code is divided into multiple modules, a little bit to digest, do not think of one breath to read the source code, this is not realistic.
This is the author to do vue3.0 source code reading parsing process recorded notes.
React source code:
Look before you leap
This is the author to read the essence of the source code. Think twice before you read the source code and ask why? Look at the source code with a problem will get twice the result with half the effort, why say so? If you do not read with problems, you will be in a aimless, blind state, in this state, especially to see boring and tedious source code, will not concentrate, for a long time will be sleepy, unable to stick to it.
Before reading the source code, first think of a few questions, with these questions to find answers in the source code,
Example ๐ฐ 1:
Here are a few questions for vue3.0’s responsive principles:
- 1
vue3.0
How to build a response,reactive API
What did he do? - 2
effect
ๅreactive
What is the relationship?effect
How to replacewatcher
? - 3 How to collect dependencies?
- 4 through
this.a
Change, how does the view correspond to updates.
Example ๐ฐ 2
As I read about React-Redux, I’ll start with a few questions:
- 1 Why in
root
Used on the root componentreact-redux
็Provider
Component packages? - 2
react-redux
What is andredux
Fit, dostate
What about changing the update view? - 3
provide
How to store the current oneredux
็store
And how is it delivered to every subscription requiredstate
Component of? - 4
connect
How do we connect our business components and then update the subscribed components? - 5
connect
How do I subscribe to the corresponding state with the first parameter, mapStateToProps? - 6
connect
How do I merge the props and redux state?
With these questions to read the source code, will be in the source code carefully to find the answer to these questions, if found the answer, and explain the principle, there will be a good sense of achievement.
3 Extract the essence
React individual functions may have hundreds or even thousands of lines, but with the exception of server rendering, __dev__ warnings in the development environment,context handling, and some judgment, etc. The real core logic code, maybe just a few or a dozen lines, so we don’t need to deduct every line of code in the source code, just need to figure out the core logic.
Take the React source code as an example:
react/react-reconciler/ReactFiberClassComponent.js
Under this file, there is a constructClassInstance method for new our component instance. This method is about 200 lines long, but after I refine it, the code looks like this
function constructClassInstance(
workInProgress, //
ctor, // ๆไปฌ็ component
props, // Props for the component
){
/* Instantiate our component */
const instance = new ctor(props, context);
/* Attach the updater object to the current component instance for component rendering update */
adoptClassInstance(workInProgress, instance);
}
Copy the code
The core code is just a few lines, so it’s important to extract the essence of the source code in the process of reading it.
4 Real bullets
Practice is the sole criterion for testing truth. If you want to understand the source code, don’t just look at it, but really run through it. So we can clone the source code on Github. Then, in critical contexts, you can use the debugger or console.
The steps are as follows:
fromgithub
Download files.
Then go to the debugger or console.
Next, pull out the source code separately and package it.
Put it into our demo project for verification.
Now we’re going to change the path. Because our package used to be in node_modules, now the path has changed, so pay attention to the path problem.
Teach students according to their aptitude
Not all framework source code requires a fixed pattern to parse. At this point the author suffered. Let’s start with the background.
In reading VUe2.0, the author adopts centralized reading, which is to start from New Vue and dig deeper into the code step by step. Finally, connect each module in series.
After reading the core principles of VUe2.0, I tried to read React in the same manner, and realized that this solution would not work because React has many modules, such as React, react-Reconciler, React-dom, and Scheduler, with thousands of function methods. Even the debugger, the effect is very small, unable to connect the functions of each module, forming a system.
Later, began to read some of the big guy’s articles, first understand each piece of dry what, what effect, and then pieces of the string up. Finally read the source code, found that the effect is very good.
Example: Vue and React
vue
Read the source code centrally
Vue source code is suitable for centralized reading, that is, starting from new vue(), initialize data, establish responsive, patch element node, parse template template, inject dependencies, mount real DOM, in one go, a line string.
react
Read the source code diversely
And react to a spread of reading method, is that you need to understand that the reconciler, scheduler, expiration time, request key frames, and so on, the specific is stem what of, what is the role, then, like building blocks, build them up.
6 Constant dropping wears away a stone
Stick to what is worth doing, and do what you insist on doing well. Since the choice to read the source code, will stick to it, THE author just began to look at the source code is also very painful, once several degrees want to give up, but then in accordance with the above method, stick to it, finally developed a good habit, now fully able to focus on reading the source code, and the process of feeling is not as boring as at the beginning.
I’ve heard of the 21-day effect, and if you stick to it day by day, it won’t take long to get into the habit of reading the source code. At that point, for example, when we try to use a new package, we can’t help but browse the source code on Github first.
Harvest and summary
About the harvest
The habit of looking at source code has persisted for almost two years, and the harvest feeling is still quite a lot. First of all, no matter from the knowledge reserve or programming writing method or design architecture, there are great progress, but also tried to write their own open source projects, and determined to maintain it.
Rux is a redux and React-Redux state management tool
React -keepalive-router Cache page route
conclusion
The above is what I feel in the process of reading source code, the road is long and I will search up and down, in the way of reading source code, can stick to it, there will be a beautiful scenery.
Hand left lingering fragrance, reading friends can give the author praise, pay attention to a wave, update the front end of the super core article. I’ll write a react-Redux source code article next.
Source code article summary
Vue3.0 source code series
-
Vue3.0 responsive principle (super detailed) 200+ like ๐
-
Full analysis of vue3.0 Diff algorithm 100+ like ๐
-
Vue3.0 Watch and Computed source code parsing 30+ like ๐
React Source code
-
React-router router 70+ like ๐
-
React-redux react-redux react-redux