This article has authorized the exclusive use of the public account of the Developer community, including but not limited to editing, marking the original rights and other rights.

preface

Thanks to the help of React, I have also made up some knowledge points of native JavaScript in the past half a year. While learning, I also slowly thought about some rationality of the current project. After reviewing, I summed up one point that must be optimized in some projects. Also this time in the face base and @suyun little sister after the discussion of a harvest, if it is helpful to everyone, might as well point a like to support the author.

What kind of code is clean

For a long time, most front ends have been complaining about the fact that it’s hard for anyone but the developer to take over the code in a project. Therefore, if the developer leaves, the piece of code will have to be refactored, and the project will easily become a high-risk project. One day, a new colleague adds a requirement, and suddenly some strange bugs will appear.

So, your code might look something like this,

So what does clean code look like? What about, literally, clean and tidy in the code? When we do most development specifications, such as Eslint, it seems like we can only get a general level of planning integrity across the entire dorm (team) as shown below, but in fact, is the code everyone writes really as clean as the code style?

Turns out, it wasn’t. The strong constraints that Eslint imposes only make the code look less confusing, which has nothing to do with code clarity, so clean code is mostly generated by developers who are constantly coding to find problems -> fix them -> summarize them.

So let’s get to the topic and share some basic ideas.

Function comments and TypeScript

Why are comments in the first tier alone?

I personally think that good code comments must be clear, it is like the introduction of the product, you can at first glance know some information about it, such as what it does, the parameters passed in, what is returned.

You know what the current constant refers to, and you know what the declaration is for. It’s recommended that in 2021, if your team is using TypeScript, don’t bother. It’s pretty straightforward to improve the quality of your code.

Code without comments is likely to be looked at in code review

Variable & Constant

TS =>

JSDOC =>

Function (method)

TS =>

JSDOC =>

The above examples of variables and function methods are used for some basic demonstrations. JsDOC is an alternative when the team is not using TypeScript.

Do you really know function methods

When writing business friends seldom pay attention to the complexity of a function method, the size of the complexity determines that he (she) people understand your code a degree of efficiency, whether the React, or Vue, even write Node, Libray are most of the above function in supporting the, so the function will occupy the WEB development is very big.

So take a look at the function, how can make the current code conditioning more clear.

SRP () function

For a single principle, the function is actually one with a bold, in most cases, the only function is to do a thing, a logic, so, in combination with the basic annotation can instantly make friend understand you this method is mainly used to do, without having to think about whether still do the other one thing.

However, the granularity of the single principle is another problem. When writing React component, if we adopt the single function principle, the functions in a component will be massive, so at this time we need to weigh the current logic level. In a proper scope, the size of things can also be applied to functions. My function may be the BFF(aggregation layer) of multiple functions, or my function itself may be used to handle an aggregation task.

Example:

The following function is typically one function that deals with two behaviors, but it’s not the same thing when you say it’s not. If you upgrade it, it’s only dealing with one thing, and it’s just dealing with Storage. Therefore, the limitations of SRP lie with the developer itself, and what level of scope you want it to deal with will determine whether your function SRP does enough.

So, we can also write it as follows, splitting set and get into two different functions.

Active return function (active stop)

For business development, often a function may need to pass some preconditions before it can flow to some of the core logic of our business. This kind of preconditions are often some condition judgment, therefore, when this kind of conditions cannot be satisfied, the following code execution or not is meaningless, just like the interview, the resume does not meet the screening conditions, read not back is a concept.

The following code: When the name and age are met, the personal information will be submitted; if not, a prompt will be provided. So like the following, there seems to be no problem. But the layers of if else don’t look very clear.

Try this. Both methods have a complexity of 5, but the quality of the reading is very different. The implementation of scheme 2 divides it into three steps. When the step goes wrong, the processing factor return in this step will be executed.

Function merge

The purpose of function merging is (to reduce duplication of code), and developers are known to be skilled at solving duplication of work and like to work once and for all. So often when writing code, the logic that can be merged is managed independently, as in code like this: Both methods call the same judgment statement.

Therefore, as shown in the figure below, we extract the same logic into a function, which returns the corresponding state after a layer of public code is stripped, and then calls to judge the state.

Cyclomatic complexity, the measure of function

I also learned about cyclomatic complexity this year. Cyclomatic complexity is the logical quantification of a function, and the relative measurement of the current function is marked with data.

In the concept of software testing, cyclomatic complexity is used to measure the complexity of a module’s decision structure, which is represented by the number of linearly independent paths, that is, the minimum number of paths that need to be tested reasonably to prevent errors. High cyclomatic complexity indicates that the code is likely to be of low quality and difficult to test and maintain. As a rule of thumb, high cyclomatic complexity is associated with the possibility of errors. 【 Baidu Encyclopedia 】

So, what do I see as some standardization of cyclomatic complexity?

The complexity of the State of the code Maintenance costs advice
1 ~ 10 normal low There is no
10 ~ 20 complex In the Optimize the logic, dismantle the molecular function
> 29 Difficult to maintain high Refactoring is strongly recommended

Here, I recommend a plug-in to you. As shown in the figure below, I clearly know a complexity state of my current function and can think about the optimization way of function changes at any time. One of the most subtle ways to improve the way developers think about their current implementation is that this plugin is called CodeMetrics, and I think it’s helpful.

For complex functions, refactoring is strongly recommended because 80% of them involve dirty code, so refactoring logic is inevitable.

Click to go to VS Code to download the plug-in

Status Remarks Maintenance

What is a state?

State information

Get some fields, such as status, that everyone experiences as being returned from the back end, but basically the value is actually unreadable, and the front end often has no idea what the state means except for the back end and the person to whom it connects. Even over time, as the demand increases, you’ll wonder what is 1 and what is 2 in status? So you can’t avoid looking at the document twice. The time itself can be saved.

The unreadable fields on the back end are actually from the entity class, but the field notes in its data table are very detailed. Therefore, the back end is absolutely capable of teasing out the current state.

Therefore, when performing state operations, add a note to the data declaration. The following figure is one of the more difficult to understand:

As grade changes, the next time you change the logic, you need to reunderstand grade.

So, we can make some friendly comments to declare and annotate the state

PS. When states can be described, it is often possible to define an array of states and return some descriptions.

Generally, it is used for the state of a Chinese paragraph.

Operating state

The above is some information state processing methods, but the operation state is often abstracted from the front end, take a very simple example: the creation page and the editing page of a form can be reused, since it is reused, it must involve a parameter to judge.

The following code, which is a very difficult thing to understand, is 1 for create and 2 for edit. This is a form that is highly discouraged.

const action = 1

if (action === 1) {
/ / create
}

if (action === 2) {
/ / edit
}
Copy the code

A better form is as follows: Then you immediately know what the parameter means.

Const action = 'create' if (action === 'create') {// create} if (action === 'edit')}Copy the code

This kind of state is often wrong in the page path value, the page component reuse.

useclassAggregate method, rather thanobject

In an example mentioned above, localStorage is often required to wrap a layer of our own, so this multiple different methods, but they operate on the behavior of a model, can be a simple aggregation group.

In ES5, before the class syntax sugar came out and the prototype class was too cumbersome, there was the use of objects to aggregate methods, which was actually unfriendly, as shown below:

However, in order to have better extension ability, a single object has no advantage over a class. Secondly, class has a better object-oriented basis, while object only manages functions as attributes. If you want to make a superset based on the current set, then object is not competent for the subset task.

Why not recommend automatic Prettier

This is a small series, and there may be others to follow, but most of the content in this article is on partial functions. This part of the article should be considered out of the business framework of a point of knowledge.

In the end, I would like to say my opinion about prettier. The tool itself is good, but in many articles, the code is directly painted in Git hook. So, what is the value of this plug-in to developers? Or was it done on purpose to make the project code look good?

So, in the end, I’d like developers to develop their own set of ESLint code specifications, be it Alibaba, Tencent… To wait, also can be a popular plug-in eslint – the plugin, I hope it’s developers keep writing (especially the novice developer), according to the standard of the current team, careful to write down go to, write behind, is single quotes, double quotes, several Spaces such rules are to plug-in to packaging and these are the plug-ins need to do. Rather than handing over functionality that can help developers to plug-ins as a vanity project.

Tool chains that don’t help developers grow are not recommended unless they are necessary.

conclusion

The seven-day clock-in campaign has started. During the seven days, I will share some summary of my project and what I have learned. As a new member of the Atmosphere team of Starbucks, I still like the gift this time. It just so happened that the task iteration has entered a relatively late stage, so I can bring you more quality articles.

This is the first time I’ve written an article outside of the framework, and it’s a great start to 2021. I hope to bring you more articles about Vue, React, TypeScript, and engineering in the coming year. If you found this article helpful, please give me a like.

In 2021, I hope everyone can become a better front-end development engineer.