Click on theClick to subscribe to the column of Cloud Recommendation Guru, get the official recommended boutique content, learn technology not lost!

Readable code can greatly improve development efficiency. A large part of the development process is spent reading code. Readable code, easy to understand and easy to change. On the other hand, unreadable code is bad to read and error-prone to change.

Here’s an unreadable piece of code:

const user = ...
const foo = (cb) => ...
const bar = (list, cb) => ...
const other = (list1, list2) => ...

if(user ? user.isAdmin : ((user.permission && user.permission.view) ? user.permission.view === true :  false)) {
  foo((res) => {
    if(res && res.ok && res.list && res.list.length > 0) {
      bar(res.list, (res2) => {
        if(res2 && res2.ok && res2.list && res2.list.length > 0) {
          other(res.list, res2.list)
        }
      })
    }
  })
}
Copy the code

The above code has these problems:

1. The name of the function does not match the function. 2. If conditions are too complex and deeply nested. 3. Callback functions are deeply nested.

Change the above code to readable code:

const user = ... const fetchChannel = () => ... const fetchArticle = (list) => ... const render = (channelList, articleList) => ... const hasViewPermission = user.isAdmin || user.permission? .view if(! hasViewPermission) { return } const { ok, list: channelList} = await fetchChannel() if (! (ok && channelList? .length > 0)) { return } const { ok: fetchArticleOk, articleList } = await fetchArticle(channelList) if (! (fetchArticleOk && articleList.length > 0)) { return } render(channelList, articleList)Copy the code

In summary, readable code has the following characteristics:

  • Consistent code style.
  • Proper naming.
  • Necessary comments.
  • No big files.
  • No deep nested code.

How do I write readable code?

Write readable code that meets the characteristics mentioned above.

A consistent code style

Consistent code style means that Spaces, indents, naming styles (humps, hyphens, etc.) are consistent throughout the project. A consistent code style, which looks neat, also reduces the cost of understanding. In a project, it doesn’t matter what code style you use. It is important that the style be consistent.

Some of the best known code styles in the front-end industry are Airbnb JavaScript Style Guide and JavaScript Standard Style. If you don’t want to mess around, you can use JavaScript Standard Style. JavaScript Standard Style features:

  • No configuration is required. The most convenient way ever to unify code style, easy to own.
  • Automatic code formatting. Just runstandard --fixSay goodbye to dirty, messy code.
  • Identify style and procedural issues in advance. Reduce the back-and-forth modification process during code review and save time.

Once you’ve determined your code style, you can use the checking tool ESLint to ensure that your code style is consistent. Before each code submission, do a check, using the tool husky. For large projects, it is too slow to review the entire project. Lint-staged only files that were modified this time were checked.

Two, reasonable naming

There are only two hard things in Computer Science: cache invalidation and naming things. There are only two things that are hard in computer science: cache invalidation and naming. — Phil Karlton

Good naming is “known by its name”. Specifically, good naming has the following characteristics: straightforward, meaningful

Good naming is easy to understand, that is, straightforward, meaningful. For example, fetchUserInfo.

Recommended: Naming of the Forbidden City

Extract the key features of the target object to name it.

Recommended naming tool: CODELF. It helps you search Github, GitLab, etc., for different names for what you want to find.

Be careful not to misspell the words in the name. Recommended tool: Code Spell Checker.

Follow industry practices

Good naming should also follow industry conventions. For example, the industry convention is to use id as the unique identifier, not identifier. I, j, and k are used for loop count variable naming.

Code style

Good naming should fit the code style of the current project. Such as: hump style.

Bad naming has the following characteristics.

Meaningless names

Nonsensical names like foo, bar, var1, fun1.

Too abstract a name

Too abstract names, such as data, RES, temp, tools. There are ambiguous abbreviations

There are ambiguous abbreviations, such as mod. You may not be able to determine whether it is mode or Module.

Unnecessary context information

// bad function async getUserName (userId) { const userName = await fetchUser(userId) return userName } // good function  async getUserName (id) { const name = await fetchUser(id) return name }Copy the code

Too long a name

Too long a name, not easy to understand. Such as: fetchGraintYoungestBoyName. How to optimize: Omit non-essential content. For example, fetchBoyName.

3. Necessary notes

Comments are explanations and descriptions of code. Good code is self-explanatory. For uncomplicated code, you don’t need comments. Writing comments that only explain what the code does is not only a waste of the reader’s time, but also misleading (when the comments and the code function are inconsistent).

Scenarios requiring comments:

  • When the code itself does not clearly state the author’s intent.
  • The logic is complicated.

No big files

Large files: files with many lines of code (more than 1000 lines). Big files, meaning the code does a lot of things, and it’s hard to keep track of what’s going on.

You can use the max-lines rule in ESLine to find large files.

Optimization scheme: divide large files into several small files according to functions.

No deep nested code

Deeply nested code that is poorly readable and “awe-inspiring”. Such as:

fetchData1(data1 =>
  fetchData2(data2 =>
    fetchData3(data3 =>
      fetchData4(data4 =>
        fetchData5(data5 =>
          fetchData6(data6 =>
            fetchData7(data7 =>
              done(data1, data2, data3, dat4, data5, data6, data7)
            )
          )
        )
      )
    )
  )
)
Copy the code

Here are a few common deeply nested scenarios.

1.The callback hell

Using callbacks to handle multiple serial asynchronous operations can result in deep nesting. Commonly known as “callback hell.” Such as:

fetchData1(data1 =>
  fetchData2(data2 =>
    fetchData3(data3 =>
      done(data1, data2, data3)
    )
  )
)
Copy the code

2. If nesting is deep

In conditional statements, if there are many criteria, deep nesting or long criteria may occur. For example, determine whether a value between 1 and 100 is an even number divisible by 3 and 5. So to write:

const isEvenNum = num => Number.isInteger(num) && num % 2 === 0 const isBetween = num => num > 1 && num < 100 const IsDivisible = num => num % 3 === = 0 && num % 5 === = 0 if(isEvenNum(num)) {// Is even if(isBetween(num)) {// between 1 and 100 If (isDivisible(num)) {// visible by 3 and 5 return true} return false} return false} return falseCopy the code

Ternary expressions can also be deeply nested:

a > 0 ? (b < 5 > ? (c ? d : e) : (f ? g : h)) : (i ? j : k)
Copy the code

3. Nested function calls

Making multiple function calls, each function whose output is the input to the next function, can create deep nesting. Such as:

// Simulate the process of scrambled eggs: buy eggs -> beat eggs -> scrambled eggs -> serve. ToTable (// step 4: Fry (// step 3: fry eggs (// Step 2: beat eggs to buy(20) // Step 1: buy eggs))Copy the code

React High-order components are nested

In applications written by React, a component may be wrapped in multiple high-order components (HOC), resulting in deep nesting. Such as:

class Comp extends React.Component {... } Wrapper5( Wrapper4( Wrapper3( Wrapper2( Wrapper1(Comp) ) ) ) )Copy the code

React Context nesting

In React applications, Context can be used to manage data sharing between subcomponents. If there is a lot of shared data and the types are different, it is easy to create a very deep nesting of the top component Context. Such as:

<PageContext.Provider value={... } > <User.Provider value={... } > <Project.Provider value={... } > <ChildComp /> </Project.Provider> </User.Provider> </PageContext.Provider>Copy the code

The optimization scheme is shown here.

conclusion

Any code that meets the characteristics of readable code mentioned in this article is readable. Of course, there are many other tricks to improve the readability of your code. Such as:

  • Limit the number of arguments to a function.
  • Limit the cyclomatic complexity of a function.
  • disablewithStatements.

For more tips on improving code readability, it is recommended to polish ESLint’s rules.

The next level of code quality is reusable code. This will be covered in the next article.

Excellent articles recommended by Mr. Jin Weiqiang:

Talk about code quality – The introduction to Learn and Copy how to Improve Front-end Code Quality

Code Quality Layer 5 – just the functionality is implemented

Code Quality Layer 4 – Robust code

“Cloud recommendation” is Tencent cloud plus community high-quality content column. Yunjianguan specially invites the top performers in the industry, focusing on the landing of cutting-edge technology and theoretical practice, to continue to interpret hot technologies in the cloud era and explore new opportunities for industry development.Click one button to subscribe, we will regularly push high-quality content for you.