Some time ago, I joined the front end group of a new business line in the company. As it is a new business line, what I do is also a small program, so THERE is almost no historical baggage. All the members in the group are the primary producers of project code

I joined the timing of late, without the experience of the first start-up phase, don’t know much about it at first, but I heard that is pretty excruciating, need to hit the pit innumerable, often need to work overtime, although the Internet industry to work overtime is the norm, but survived the initial stage is much better now, it makes me glad and regret, fortunately I don’t have to work overtime so late, unfortunately, Not being involved in the initial stages of a new line of business, I wonder if I’ll ever have the opportunity again

However, it was not too late for me to join, and there were still many places to fill in the project. After reading the code during this period of time and the problems encountered in the process of requirements, I temporarily summarized some small experience about the project architecture or the construction of maintainable code from the front end.

Componentized development best practices

Now that front-end componentized development is basically mainstream, it’s natural to follow some componentized best practices now that it’s componentized development

Do not exceed the total number of lines of code in each component file400line

As to why is 400 lines, this number is I saw on a technical article, as to what I forget, but I don’t know why is very impressive, always remember, and according to my many years of experience, this number is accurate, general or can’t more than this number, or hovering in the figure, Or a lot more than that

These are all very well understood, since it is componentized development, if a component file is too large, there are dozens of methods, dozens of data data (if the VUE framework is used), it means that the component is likely to contain too many function points, can be further refined into a number of single function of the sub-components

Too many methods and data data, for developers, on the other hand, is a kind of torture, if nothing else, just to name these methods and search is a hassle, as for maintenance in the future, it is the existence of the nightmare, even at the beginning handwritten procedures with the code, a period of time to maintain the code him again, Nine times out of ten, he is treading on thin ice. Even though he has confirmed many times, he is still worried that his modification of a certain data or method will cause unpredictable damage to some previously hidden logic, so he tests and checks dozens of methods and data over and over again

I’ve seen components that contain more than 70 pieces of data

This kind of situation is good, encounter irresponsible program apes, may direct the trouble, just find a place in a lot of code to write down their new code, check didn’t check immediately measured online, because anyway on he used to be so much demand, accidentally messed up one of the requirements of logic, who, who knows?

This is just adding new code to the old code. If it is active code that expires before you go offline, or if you delete useless logic, it is even worse. Dozens of methods and dozens of data are intertwined. Does deleting this seemingly useless code cause other useful code to fail? Forget it, do not delete, anyway, the back-end interface has been closed, this code is not displayed, temporarily on the above bar. As everyone knows, this so-called temporary, is the seas run dry and rocks crumble forever

Grandpa, grandpa, did you really write this code?

As a result, there are more and more useless code on the page, old code and new code complement each other, and the size of the file increases rapidly. With the passage of time, the original fresh code base, which was packed with light, is gradually saddled with one historical burden after another, and then is scolded by the people who take over from behind.

There is no historical burden in the world at all, but as many people lose their historical burden, so do they.

Do not exceed 100 lines per function

If you think about it, a component should be no more than 400 lines, and a method should be more than 100 lines, how do you write it? , of course, the number 100, according to my experience, here are more accurate, more than the number of rows, thinking, isn’t this method contains too much logic, follow the principle of function function of a single, don’t let a method function contains too much logic functions, is used to pull data, so it only pull data, is used to integrate let it only integration of field, Don’t do anything else

What a sexy butt. Promise me you won’t use it to pull shi, okay?

As A result, the method of function function is clear, not only to maintain need not fear the hand and foot, but also increases the reusability of methods, for example, A method includes pull the function of the basic data page, then demand iteration, another later add B method based function also need to pull A page, just before you want to reuse A method, It is found that in addition to the code of pulling data in method A, there are also many ways to judge whether to display pop-ups, modify data fields, bury points and so on. else… So the person who wrote method B, either to avoid trouble or to find it impossible to reuse, had to rewrite the pull function again

Of course, this is just a principle, in the actual requirements, if the two functions are closely related to the logic, you can also write in a method, in short, under the premise of reference to this principle, flexible

Define methods and data as birds of a feather

Which have similar capacity or work together in a function method and data of the best defined near the location, convenient search, a feature control by those methods and data, a data volume contains which fields are all be clear at a glance, later to modify or delete, can do have answers, and won’t be missed

There are 107 more like me

For example, lifecycle methods are written together and in the order of execution, not intermixed with custom methods; Custom method also have to be classified according to their respective functions, such as the request of the interface methods wrote together, write switch page popup window method together, has nothing to do with the business tool method on a page to put together, the user information data is defined in the near location, if you are using the vue, has nothing to do with the template rendering variables, then, don’t put in the data, It not only improves rendering performance, but also makes it easier to distinguish variables

// All tools and methods are put together
// The amount is transferred into yuan
fen2yuan(fenNum) {
  return fenNum / 100
}
// Modify the link protocol
changeUrl(url) {
  return url.replace('http'.'https')}// User information data is defined in close proximity
// Of course, you can even define the following data in a large object
let avatar = 'https://avarat.com/a.png'
let userName = 'Ming'
let age = 19
Copy the code

By the way, it is best to write CSS according to the same rules. The CSS code determines the order of the elements, such as the left top, the color background, the font weight, and the color weight. Those that have the same function are best written together

In addition, I used to put the properties that can cause page reflux in front of the properties that can cause page redraw, and the higher the degree of influence on the elements, the more in front, as to what is called the degree of influence I don’t know, the following is my general CSS properties order, you can understand

<!-- positionAt the front-->
position: relative;
<!--And then the referencepositionProperties to locate-->
top: 100px;
left: 10px;
<!--And then the width and the height-->
width: 100px;
height: 100px;
line-height: 20px;
<!--And then themargin padding -->
margin: 10px;
padding: 20px 30px;
<!-- font -->
font-size: 20px;
font-weight: 700;
<!-- border -->
border: 1.px solid red;
border-radius4:px;
<!-- background -->
background-color: pink;
<!-- z-index -->
z-index: 10;
Copy the code

At the beginning, I was not used to this slightly restrictive writing method, but after a long time, I got used to it. The writing order of these attributes, I wrote quickly in turn without thinking. Sometimes, I even saw the messy writing by others that did not accord with my habit of writing, and I would change it by hand.

The advantage of doing this is that it is easy to find and maintain. If you want to change width, it must be at the front of the CSS attribute sequence of the element. If you want to change background, it must be swept from the back. More than once I’ve seen an attribute in the code base, like a background written twice, a background written in the top half of the attribute sequence, and then maybe because the element has too many attributes, the person who maintained it didn’t see the backgound, or it was too messy and didn’t want to look at it, So I just put one at the end of the property sequence

Aside from the above benefits do not say, at least this kind of order, order of writing order, for some astrological people, looking at is also pleasing to the eye, invisible in can also let oneself and outside those coquettish whore

There is no point in studying hard and not being pushy

Necessary and accurate comments

For long-term maintenance projects, necessary and accurate annotations are essential (but not for writing novels)

If you write a line of code, you’ll probably know in three days why you wrote it, what the variables mean, and what they do, but what about in a month, six months, a year? And even if you did, what about the others?

I don’t know what this code does, but it’s not normal to delete it, okay

If let you maintain a you already do not remember who wrote, what also don’t know what mean code, certainly the first thing you should do is to look at the code, to understand what you mean, then to the follow-up maintenance, and for some more complex logic, such as homepage, embeds the dozens of pop-up window, The dozens of pop-ups correspond to dozens of function points, and it takes you A long time just to figure out the logic of A and B pop-ups, because you need to modify the logic of one A popover and prioritize the other B popover.

If you have an exact comment on the line of code above it, even if you have to read the code later, you’ll understand it faster and more accurately than if you don’t have the code

One piece of code saves time, but what about ten? How about the code for a file? What about the amount of code in the entire code base?

So, don’t think comments dispensable, in addition, you write the code is for people to read, and technical personnel, so to understand statements of choose and employ persons, if your description ability is not enough to let you in a line description is clear, then add a line, in a word must be described clearly, a little knowledge of the annotation is don’t write, These days, most of them use automated packaging and compilation tools (such as WebPack), and comments are automatically removed at the end of the project release phase and don’t take up a lot of code

It is best to name variables and methods in a regular way

Also for better reading experience and to avoid transition comments, the best comment is to let the code “speak” for itself, that is, to name it regularly

For example, the variables used to store arrays have List as their name suffix, the object variables used for certain information have Info as their name suffix, and the variables used for judging certain logic have is as their prefix. In this way, the general function of the variables can be known at a glance, avoiding the stupid thing of making an object of type object call map

const namesList = ['xiaoming'.'xiaohong']
const userInfo = {
  name: 'John'.age: 20.gender: 'male'
}
const isEven = 10 % 2= = =0
Copy the code

In addition, in order to more easily reflect the function point of the method, the method name should not be too “broad”, such as the pull data method, it is best not to name the method like getData, because if there are other pull data methods in the component, it can be confusing. It is not immediately clear which data interface this getData is for, and it should be further precise to the corresponding interface, such as named getUserData

There are many detailed solutions to naming variables and methods. Why not write two articles on them

Common functions should be encapsulated as components

Generic components, it is best to determine the function points, encapsulated into a unified generic component, the generic component must cover most of the common function points, otherwise it is better not to

Larger ones, such as pop-ups, may include structures such as titles, close buttons, content, and masks. Smaller ones, such as page masks, include a mask style for the body, which should be taken into account when encapsulating the component

I’ve seen in a component that contains multiple bullet window, but no popup window of encapsulation general components, and the same elements as well as the style was written several times, the deepest impression is the mask layer elements also appeared several times, each pop-up wrote a mask layer style, wrote knows, alone this one mask layer styles have several lines, why bother to zai

DRY principle

Don't repeat yourself

This one can be used in conjunction with the previous one. No matter what code you’re writing, whether the requirements are long term or short term, you’d better follow this rule as a good programmer, right

DRY here, not only refers to the code letters completely the same, also is the same logic, here, for example, form validation is a very common scenario, general validation of the method are without thinking of several or even dozens of if statements lined, neatly imposing manner, but the problem is a few if statements together may not be too obvious, It’s hard to touch your G-spot, but can’t you feel awkward with dozens or even dozens of if statements piled up?

if (age > 19) {
  // ...
}
if (name.indexOf('zhao')) {
  // ...
}
if (gender === 1) {
  // ...
}
if (weight > 75) {
  // ...
}
// It goes on forever
// ...
Copy the code

As long as I copy and paste fast enough, the bug can’t catch up with me

About form validation this thing, there is a very good article, you can refer to

The necessary isolation between separate business codes and between business and non-business codes

Business code to if… Littliness is one of the main signs, multiple requirements of the business code mixed together that means several times the littliness if… Else, if again in these if… Else hidden cat inserted into non-business code, so congratulations, now you get this code, in fact, has a long spread in the river’s lake famous name: spaghetti code

It makes sense that isolating individual business code directly reduces hair loss and indirectly reduces bug occurrence

The general project is a long-term iteration, a page may be piled up dozens of requirements of the function point, each function point corresponds to several large sections of methods and data, and these requirements may have been revised several times from the creation to now, perhaps some businesses are interdependent and overlap

If all the methods and data contained in these businesses are put together, it is sour… Ah, does this method belong to requirement A? If so, why does it include the data required by B? Why is the method of C requirement called here? Does the method required by C modify the data required by C? Doesn’t look like much, does it? Forget it, should be, first write like this, wait for the test to mention the bug again…

It’s not because you need more, it’s because the code you write gives you more work to do

Location-independent elements gather to write

If there are few elements on the page, there may be no difference, but when there are a lot of elements on the page, such as the site home page, commodity details page these more important pages, it is easy to feel out

Auxiliary elements like modal popover, toast and so on, there may be many on the page, this element is generally irrelevant with the position, style Settings are position: asbolute or position: fixed; It is recommended to find a fixed place to gather and store these elements, such as the top or bottom of the page, and write annotations to facilitate searching and modification, as well as statistics. It is a hassle to maintain these elements if they are interwoven among various DOM

<! -- Novice gift guided missile window -->
<ModalA />
<! -- Award popover -->
<ModalB />
<! -- Tips for new people -->
<ToastA />
<! -- Lack of qualifications hint -->
<ToastB />
<! -- Risk user Tip -->
<ToastC />
Copy the code

Get rid of unnecessary code

This includes invalid code, commented code, and unnecessary debugging code

Made active page should all know, this kind of activity operation page is generally a short life, but to pay a lot of energy, activity code may be invalid directly after logging off, in most cases the failure of the active code page will not valid logic impact, so the demand of rushing into the next procedure apes, based on the principle of more than the less about, It’s quite common, at least in my experience, to allow invalid code to remain on the page until the end of time

Some requirements during the development phase of frequent change of hardly had worked so hard to write the logic of the die are uploaded to the online server, become angry from embarrassment program apes unwilling fall hair doesn’t even have a little achievement, so tactfully press Ctrl + / keyboard shortcuts, fantasizing about this is seal code always has been discovered that day, little imagine, And until the end of time, this kind of thing at least from my experience, very common

Although some automated packaging and compilation tools support the removal of debugging code such as console.log and debugger, the problem is that this code is always present during the dev phase, and everyone adds 5 console.log to each requirement, so it only takes 10 people to do it. The console can appear 50 lines of console.log, especially these console.log basically uphold the principle of writing where there is a position, even if you want to delete it also takes a lot of time, but the pain of the program ape did nothing, first saw dozens of lines of others on the console. Then find the one you need in a pile of console.log, and when the requirements are completed, incidentally, on the basis of the original dozens of console.log, and contribute their own strength, this kind of thing at least from my experience, very common

Editor each shows a line of code is invalid, console each line of the console output. The log, will cost a certain power, tens of millions of programmers in the world, many a mickle makes a muckle, and enough to increase the global greenhouse effect, accelerate the two levels of glaciers melting, poor baby baby polar bear and penguins can’t find mom and dad, there really is good in the world there true love in the world, Please press backspace or Delete firmly

Good communication to avoid ineffective output

Never believe the PM when he says that the requirement will definitely not change

PM change requirements we can’t discourage, but we can clear the existing requirements, don’t write an invalid code, thus further to avoid the long notes, keep more hair, don’t wait for fast online, only to find that he was mistaken for a logic, or less wrote a section of logic, is the most hateful white wrote a piece of logic

Fault-tolerant code

No bug-free code in the world, as long as you write is not a demo, fault-tolerant processing must then be prepared to code, because you never know interface is returned to you | or 丨 (experience, the stem see what make you stunned Bug?)

There are other things that might not be called errors, such as the initialization of the page data. Before the data is retrieved, the page may render undefined. For a better user experience, it is better to give a better initial value

Follow established norms

Multi-person collaboration specifications are important, as evidenced by the popularity of both JSHint and ESLint

For a project, specifications can range from es version and indent type to page structure and component split. You can either copy the mature specification directly or customize the specification. But whatever the specification is, it should be followed

There is a kind of effect called broken window effect. Different styles appear in this project. The first impression of people who come in later is that the standard is not so rigorous, and it is ok to break it occasionally. So different styles accumulate more and more, the specification is out of the question, from the beginning is not stable, do you still want to suddenly hard half way?

You may not like the divisions of page structure project now, also can think the classified methods of routing is SB, but since you had no objections raised no objection when formulating the specification (either forgotten or ignored or no opportunity to ask, anyway you didn’t oppose), so have to abide by, or you can try to change the specification, But make sure, for example, that after the new specification is developed, all the old specifications that existed in the project are changed to make sure that the code style is uniform, and you know who does the dirty work.

You pick your own shi, you eat it on your knees

Regular code reviews

It is difficult for us to find our own mistakes, otherwise we would not be so easy to break. Whether it is a deviation in the code specification or logic, some errors may never be recognized if others do not point them out in time. Regular code review can solve this problem

However, although the code is good, there is no need to review the code too often, otherwise it will only become a burden, everyone is so busy, who has nothing to help you review the code every day

Necessary trample pits with experience documentation

This is very important, no matter what you use a framework, to write a small program or webview, certainly there are all kinds of pit, if you have any historical baggage don’t want to make the old code, so the new rev project will treat, rewrite the document will be written, don’t be frightened by this trouble, but wait for new people to join, or simply is handed over to others, So you know what it’s like to knock a code and hand over a crematorium

summary

I have ever seen a post that the main idea is that most of the things that the front end does can be done by five years of experience, outsourcing or interns. Why do people with five years of experience get paid more?

And I was bored, and I said, The problem is not only on the front end, back end, a variety of domains such as the client will give you the illusion, I also think so before, and then one day when I saw the same bug, leader of the accurate positioning and convenient to solve saw at a glance, and interns scratching the most, not only failed to understand what is going on, even introduced a few more bugs, I knew I wasn’t getting all that money for nothing

Of course, most people with work experience earn more money not just because they can fix bugs faster, but also because some people are naturally gifted and have worked for only one year but are as good as others in three years, and some people have worked for only one year