Clean Code Applied to JavaScript — Part I. Before Your Start

This article, the first in a series, takes an in-depth look at the oft-mentioned topic of “how to write clean code in JavaScript.”

In this series, we’ll introduce and discuss techniques for writing clean code that every programmer should know, master, and apply to the JavaScript/TypeScript language.

Introduction to the

First, understand some concepts about writing clean code.

  1. Code smelly and refactoring

A bad taste in code is a symptom that often corresponds to a deeper problem in the system – Martin Fowler

The smell of code is a factor in technical debt – Robert C. Martin

In my opinion, Martin Fowler and Robert C. Martin are compatible, with Fowler identifying code stink as the trigger for system problems and Martin pointing out that code stink can cause side effects.

  1. Technical debt

Technical debt is a concept in software development in which developers compromise when they should be using the best solution to speed up software development by switching to one that speeds up software development in the short term, thereby imposing additional development burdens on themselves in the future.

So, just like life itself, the ideal situation is to be debt-free and in a healthy financial position (with experienced programmers and infrastructure in place to ensure that the development process doesn’t have a negative impact). However, in real life, sometimes we need to take out loans to go to college or buy our first car, we will get into some affordable debt and then need to pay a little interest. A similar situation exists in software development, where we must pay off the technical debt left over from the past. No one would buy a multi-million dollar house without savings and employment, and unpayable debts would lead to personal bankruptcy. In the same way, unpayable technical debt can lead to software development failure.

Code refactoring is the process of reorganizing existing project code without changing its external behavior.

  • Code refactoring improves the non-functional properties of the software
  • Benefits include improved code readability and reduced complexity
  • These can improve the maintainability of the source code
  • Create a clearer structure to improve scalability

Before we get started

Before I start with examples of neat code written in JavaScript, I have to make a few suggestions that are critical to team work.

Code readability

The code must be readable to humans. Don’t worry about how the computer handles it, because there are many tools to convert our code (compilers). So, most importantly, the code will be human-readable, because your longest job when you’re developing code is to read it, not write it.

Each of the following examples defines an array to store users. Which of these three examples is more readable? Which one takes less effort to read? So this is how you should organize your code.

    const users = [{ id: 1.name: "Carlos Caballero".memberSince: "1997–04–20".favoriteLanguageProgramming: ["JavaScript"."C"."Java"] {},id: 2.name: "Antonio Villena".memberSince: "2014–08–15".favoriteLanguageProgramming: ["Go"."Python"."JavaScript"] {},id: 3.name: "Jesús Segado".memberSice: "2015–03–15".favoriteLanguageProgramming: ["PHP"."JAVA"."JavaScript"]}];/ * * * * * * * * * * * * * * * * * * * * * * * /

    const users = [
    { id: 1.name: "Carlos Caballero".memberSince: "1997–04–20".favoriteLanguageProgramming: ["JavaScript"."C"."Java"] {},id: 2.name: "Antonio Villena".memberSince: "2014–08–15".favoriteLanguageProgramming: ["Go"."Python"."JavaScript"] {},id: 3.name: "Jesús Segado".memberSice: "2015–03–15".favoriteLanguageProgramming: ["PHP"."JAVA"."JavaScript"]]},/ * * * * * * * * * * * * * * * * * * * * * * * /

    const users = [{
     id: 1.name: "Carlos Caballero".memberSince: "1997–04–20".favoriteLanguageProgramming: ["JavaScript"."C"."Java"],}, {id: 2.name: "Antonio Villena".memberSince: "2014–08–15".favoriteLanguageProgramming: ["Go"."Python"."JavaScript"],}, {id: 3.name: "Jesús Segado".memberSince: "2015–03–15".favoriteLanguageProgramming: ["PHP"."JAVA"."JavaScript"],}];Copy the code

Write code in English

First of all, I am not a proficient English speaker. One of the great difficulties I have encountered in this industry is that I can hardly carry on a good and interesting conversation in English compared to my native language. But in class, I make my students have to write code in English, and I write all my code in English. Even using bad English is far better than using your native language, unless you are very lucky and your native language is English itself. The reason for this is that English is now used in business activities around the world. You may or may not like it, but everyone in the world understands that English is the language to communicate with another country, and as I told you before, you spend most of your time reading code. Imagine reading code written in a language you don’t have access to, you won’t know the names of variables or functions, all the code is encrypted to you.

Therefore, you must develop in English, even if it is not your first language. We need to learn English on the job. Although English is not my first language, I read and write English every day. Of course, there are occasional mistakes, but we can understand each other, because when using a language, the most important thing is to get the meaning across.

Try to infer what the following code snippet does. That said, the code snippets below are written in different languages and English (obviously, if one of the sample languages is your native language, you can quickly understand it). If you’re familiar with any of the following languages, Google Translate into languages you don’t know and try to deduce what the code does.

 const benutzer = {
     id: 1.name: "John Smith".mitgliedVon: "1997–04–20"}; Gehaltserhohung (benutzer,1000); 

    / * * * * * * * * * * * * * * * * * * * * * * * /

    constU ż ytkownik = {id: 1, imi ę :"John Smith"The cz ł onekZ:"1997–04–20"}; WzrostWynagrodze ń (u ż ytkownik,1000);

    / * * * * * * * * * * * * * * * * * * * * * * * /

    const user = {
     id: 1.name: "John Smith".memberSince: "1997–04–20"}; increaseSalary(user,1000);
Copy the code

Team collaboration

Once upon a time, there was a programmer working on a software project… Once upon a time, this was a beautiful story! When we started learning about software development, it was really one person facing the computer and writing code to solve problems. But today, it’s no longer a case of one person building a piece of software.

Therefore, we must learn how to work in a team. The following points are usually controversial:

  • Format code with Spaces or tabs
  • Write the braces on the next line next to the name of the function
  • Whether to place a semicolon at the end of the statement

Are you following these discussions? Sorry, these discussions are ridiculous. Because all teams will have a common standard, the code formatting tool will change the code to a consistent style.

When a programmer opens a project file and starts reading the code, he can’t deduce whether the code was written by himself or a colleague. Don’t panic, there are powerful version management tools, such as GIT.

Therefore, to work directly in a team, we need:

Instead of specifying a specific IDE for development, you can configure a standard.editorConfig file to let each team member use their favorite IDE. While not everyone uses WebStorm, VSCode, or Eclipse,.EditorConfig helps developers define and maintain consistent coding styles across different editors and ides.

 root = true

    [*]
    end_of_line = lf
    insert_final_newline = true

    [*.{js,py}]
    charset = utf-8

    [*.py]
    indent_style = space
    indent_size = 4

    [Makefile]
    indent_style = tab

    [*.js]
    indent_style = space
    indent_size = 2

    [{package.json,.travis.yml}]
    indent_style = space
    indent_size = 2
Copy the code

Lint allows us to make rules to check for formatting errors in code. Each language has its own version of Lint, which must be configured and used within a project. Sometimes there will be projects where the code doesn’t have the rules to configure the code the way you like, but you can still code this way and eventually format the code through the IDE to save some time.

 {
     "globals": {
     "myModule": true
     },
     "env": {
     "browser": true
     },
     "rules": {
     "no-unused-vars": "error"."quotes": ["warning"."double"]}}Copy the code
    const a = "a" ;
    const b = a;
    const c = b;
Copy the code

There is a tool widely used in the industry called Prettier, which changes the format of our code in real time (a plug-in for the IDE) according to linter’s rules. This allowed us to focus on the problems we had to solve, and in addition, we generated clean code by being a united team.

conclusion

In this article, I have summarized a few basic points to focus on before doing clean code. These points apply to any developer.

  • Write readable code. Since we spend a lot of time and effort reading code, readable code makes it easier to understand.

  • Write code in English. Because it is currently an international language, only then can we share the code with anyone in the world.

  • Teamwork. Set common rules, rely on tools to keep the team’s code style consistent, and make the entire project look like it was written by one person, eliminating individual code styles.


The translator’s note:

This article is the first in the whole series. It was put in the final translation, but it does not affect the reading experience of the article. So far, all the articles have been translated. Almost all of the tips and suggestions reviewed in this series can be found in the book “Clean Code” by Robert C. Martin. In order to make the translation more accurate, I also referred to the contents of this book in the process of translating the article. Carlos Caballero is a PhD computer scientist who lives and works in Spain. As he says, the principle of clean code is not limited to JavaScript, but applies to all development languages.

When it comes to writing code, some people say that written code is as elegant as poetry, while others joke that the code handed down from the family is like a mountain of shit. A lot of times, it’s not that people don’t want to write elegant code, it’s that they don’t know how to write elegant code. In Code Review, often see some strange Code, the Code is naive, redundant. Therefore, it is necessary to learn and master the principles and techniques of clean code, which is the fundamental purpose of translating and learning this series of articles.

  • How to clean JavaScript code – Variables
  • The Clean path to JavaScript code – Exception handling
  • The Way to Clean JavaScript code – Complex judgment
  • How to clean JavaScript code – Function section
  • How to clean JavaScript Code – Refactoring
  • How to clean JavaScript code – Comments
  • Simple practice for writing clean React code
  • Simple tips for writing a concise React component

Finally, follow the official account of “KooFE Front End Team” and reply to “The Way to Clean Code” to get the book “The Way to Clean Code”.