This is the section on how to Write good Code from my Very Simplified Introduction to the Front End Self-study Guide which is designed to “give people who are getting into the front end a very simplified learning path” and the goal is to “get the reader up to the basics of the job” and it’s all based on my own experience if you like, Please do not hesitate to like 👍 and forward 🚀 your support is my biggest encouragement and motivation to update

Code is written for people first, even if not for others to see, you also want to be able to understand.

In the early days of my programming career, I read more books on programming, such as “Complete Code” and “Clean Code”, rather than books on specific technical details.

In this chapter, I’ll start with the underlying logic of writing good code.

As opposed to articles that teach you how to optimize your code, by understanding this, you’ll be able to find the logic behind each optimization, which will naturally lead to better code.

Boy Scout rule

I first encountered this concept in a book called The Code Clean Way, and the entire concept was one sentence:

Leave the camp cleaner than when you came.

Every time you take a piece of code and finish it better than when you took it, the project will be less riddled with bad code.

Cleaning doesn’t have to be a lot of work. It might just be changing a variable name, splitting a function that’s a bit too long, eliminating a bit of repetitive code, cleaning up a nested if statement.

Embracing this idea doesn’t mean you should do it all the time, but keeping it in mind will only make you better at what you do, programming or not.

Six simple ideas

I follow a few simple ideas about how to code.

1 Clear naming

Good code clearly states the logic it executes, which is called “self-explanatory code.”

Self-explanatory code first requires you to declare variables, methods, etc.

I’m not a big fan of naming your variables or methods in English, as long as the programming language supports it, you can name your variables or methods with any “character” you like.

One thing to note, however, is that you should fully state what a variable or method represents.

Don’t use abbreviations that you don’t understand just to save trouble.

For long names, the editor prompts you for completion, or you can double click to select the variable and copy it.


// bad
function change(bool) {
  value = bool;
}

function baDXFangBX() {
  kaiBX();
  fangDX();
  guanBX();
}

// good
function putElephantIntoFridge() {
  openFridge();
  putElephantIn();
  closeFridge();
}
​
function baDaXiangFangJinBingXiang() {
  daKaiBingXiang();
  fangJinDaXiang();
  guanBiBingXiang();
}
​
functionPut the elephant in the refrigerator () {open the refrigerator (); Put the elephant (); Close the refrigerator (); }Copy the code

Clear semantics let you see any line of code, any variable can intuitively know what this thing is doing, without you need to find variable declaration, or use of the place, to know the specific function.

Straightforward semantic code

The following two pieces of code have the same meaning, but if you look at forEach, you can see that each element in the data is being processed.

for (const item of array) {
  // do sth
}
​
array.forEach((item) = > {
  // do sth
})
Copy the code

You can try to see which of the following codes makes more sense.

// first
const target = array.find(item= > item === 0)
if (target) {
  // do sth
}
​
// second
const hasTarget = array.map(item= > item === 0 ? item : undefined).filter(item= > item).length > 0
if (hasTarget) {
  // do sth
}
Copy the code

The first paragraph means find an element equal to 0, and if so, do something about it.

The second piece of logic is to find the element equal to 0 in the array, filter and determine the length of the array, and if the filtered array is greater than 0 (there are elements equal to 0), do something.

While both pieces of code do the same thing, the second one is a little more mouth-twister.

3 Modular code

Modular code means breaking up your code into separate “modules”, each of which has its own meaning, as large as the entire project or as small as a single line of code.

Split method

It is common to split multi-line statements into methods. This allows multiple lines of logic to be expressed in one sentence.

This is part of the code THAT I took from the project. The last four lines are set flags, set state, trigger the default selection event, and calculate the cell column width. Make hundreds of lines of code in this paragraph, condensed into “four sentences”.

function dealRoomData(data) {
  // ... other codes
  
  this.setCombineFlag(selectedRooms, fields);
  this.setCombineStatus(fields);
  this.emitSelectionChange();
  this.calculateCellWidth([]);
}
Copy the code

Align the code

In addition to the splitting method, partitioning code is a way to modularize code so that it has its own meaning in a particular section of the file.

Whichever of the following approaches you use is fine, depending on the overall project style.

But in either case, the idea of modules is implicit.

For the first, fuction’s initial f is aligned with}, in this whole area, which is the logic of foo.

The second one is also, the one between the braces is. (PS: JS will encounter auto-complete semicolon caused by the bug, so the first type is preferred)

// first
function foo() {
  // other codes
}
​
// second
function foo()
{
  // other codes
}
Copy the code

The same is true for labels, which contain the same functional content in a closed area.

<component-name
  :disabled="disabled"
  class="some-classes"
  :value="value"
  @change="handleChange"
>
  <other-component></other-component>
  <other-component></other-component>
</component-name>
​
<component-name
  :disabled="disabled"
  class="some-classes"
  :value="value"
  @change="handleChange"
/>
<other-component></other-component>
<other-component></other-component>
Copy the code

Finding the attribute part of the component-name tag all at once is not intuitive, at least in my opinion.

In my head, I need to compare this area and understand, “Oh, this code is together.”

// first
<component-name
  :disabled="disabled"
  class="some-classes"
  :value="value"
  @change="handleChange"/>
<other-component></other-component>
<other-component></other-component>
​
// second
<component-name
  :disabled="disabled"
  class="some-classes"
  :value="value"
  @change="handleChange">
  <other-component></other-component>
  <other-component></other-component>
</component-name>
Copy the code

For function calls, as well as JSX, I align the parentheses (and) to form a region that “closes” a piece of content.

this.selectedRooms.forEach((block) = > {
  block.children.forEach((room) = > {
    this.resetRowPrice(room);
  });
});
​
function isMoreThanCurrentDate() {
  return (
    time.getTime() > new Date().getTime()
  );
}
Copy the code

Let each line of code have its meaning

In addition to the above two cases, you should even make each line of code have its own meaning.

Take the following code for example.

In the case of component properties, each row represents setting a property. Just scan it vertically to see which properties are set or not.

And method call, a few parameters pass is what content, also can see intuitively.

<component-name
  :disabled="disabled"// Set the disable attributeclass=Class class1 class2 "// set class class1 class2
  :value="value"/ / bindingvalue
  @change="handleChange"/ / bindingchangeEvents / >

renderSomeComponent(
  id,
  getName(someCondition, anotherCondition),
  age,
  icon,
  getAddress(id, name, age)
)
Copy the code

The following code is something I’ve actually encountered in my projects, where you can’t immediately see what properties a component has or what parameters a method has.

You have to look at them one by one, and you even need to distinguish which parts are obtained by calling the method.

<component-name :disabled="disabled" class="class1 class2" :value="value" @change="handleChange">
  
renderSomeComponent(id, getName(someCondition, anotherCondition), age,
  icon, getAddress(id, name, age))
renderSomeComponent(anotherId, getName(someCondition, anotherCondition), age,
  icon, getAddress(anotherId, name, age))
Copy the code

4 Appropriate notes

When code can clearly express what it does, there is no need for additional comments to explain it, but that doesn’t mean you never need to write comments.

The code can only tell the reader what the code does, but why it does it can only be explained through comments.

This is the code for the column width adaptive part of a table in a project, and the comment here explains why this is done – to prevent the cell contents from being blocked.

// Calculate table column width.
// Prevent cell contents from being blocked due to insufficient width.
calculateCellWidth(currView) {
  // Compute the cell column width code
  this.checkTableWidthGap();
},
  
 // When the body width and header width are less than one cell, add the remaining width.
checkTableWidthGap() {
  // Column width complement code
},
Copy the code

There are also comments that programmers use to communicate with each other ðŸĪŠ.

/*** * this company has no year-end bonus, brother don't expect, also don't come, I'm ready to resign * in addition, this project has a lot of * bugs * you can't last long, bye bye! * /
Copy the code

5 Single Responsibility

A file maintains a class of code, a method maintains a function, an area of code does one thing, a line of code means one thing.

When following such a simple idea, from a single line of code to an entire project, it makes sense.

Modularizing the code mentioned earlier is also intended to keep the responsibilities of each module single.

6. Reduce repetition

When there are duplicate parts of code, it’s time to think about splitting.

When related properties and methods are split together, they are classes; Template + logic + style split together, is the component; The function-related code is split into a single file, called a module file.

Classes, components, modules, frameworks, or encapsulation operations are designed to aggregate interconnected code into one “module” after another.

These encapsulation operations aggregate large chunks of code together to keep responsibilities single and to make it easier to maintain or extend functionality later.

For example, iterating through a set of elements and setting values. For code like this, it is perfectly possible to declare a variable at the top of the loop body and value it.

There’s only two lines here, and I’ve seen seven or eight lines of code that do this, and when the logic changes, like I + 1, everything has to change once.

for (let i = 0; i < people.length; i++) {
  somebody.id = people[i].id;
  somebody.name = people[i].name;
}
Copy the code

The same goes for splitting. If the same piece of code logic needs to be changed, everything needs to be changed once.

If we want to carry out internal transformation, as long as the internal function of the whole module is consistent, there is no need to worry about the original function being affected.

Code quality indicators

Finally, I’d like to give you a list of seven metrics for code quality.

There are seven commonly accepted standards:

  • Maintainability
  • Readability
  • Extensibility
  • Flexibility
  • Simplicity
  • Reusability
  • Testability

Among them, maintainability, readability and extensibility are the most mentioned and the most important three evaluation criteria.

conclusion

The six ideas shared today are enough to give you a foundation for writing good code. Leave it to Lint to decide whether to write semicolons, Spaces before and after parentheses, and no more than one line of code.


Follow me for updates on this tutorial and if you have something you’d like to share in the comments section, or add my VX: vWetoria. If you like, leave a thumbs-up at âĪïļ to support me. Or retweet it and let more people see it. (low low ◡) ノ has