Clean Code Example of JavaScript code

Translator's note: clean code written to avoid excessive BUG.

In this paper, paraphrase, belongs to original author

Quotation

As a developer, if you care about code quality, in addition to carefully test code can execute properly outside, but also focus on clean code (clean code). A professional developer will consider how to write code, not just the machines themselves or be able to read the future from the point of view of others and easy maintenance. Any code you write will have a great chance to be reconstructed again, hope that the future reconstruction of the individual code will not think this is a disaster.

Concise way the code can be understood as: Code self-explanatory (and comment less), developer-friendly (easy to understand, modifications and extensions).

Think before reading other people's code, the following remark how many times?

"WTF is that?"

"WTF did you do here?"

"WTF is this for?"

Image below is vividly describes this situation:

img

"Clean Code" author Robert C. Martin (Uncle Bob) said such a thing.

Although bad code can run, but it is not clean, it will throughout the entire development team to kneel

This paper stresses the tidy road JavaScript code.

1. strong type checking

It recommended ===instead ==to determine whether equal

// 如果没有妥善处理的话,可能会出现和预想不一样的结果
0 == false; // true
0 === false; // false
2 == "2"; // true
2 === "2"; // false

const value = "500";
if (value === 500) {
    // 不会执行
    console.log(value);
}

if (value === "500") {
    // 会执行
    console.log(value);
}

2. Name the variable

Variable naming try intuitive, easy to find; but other developers are also easy to understand.

Bad naming:

let daysSLV = 10;
let y = new Date().getFullYear();

let ok;
if (user.age > 30) {
    ok = true;
}

Good naming:

const MAX_AGE = 30;
let daysSinceLastVisit = 10;
let currentYear = new Date().getFullYear();

...

const isUserOlderThanAllowed = user.age > MAX_AGE;

Do not use extra meaningless words to a combination of name

Bad naming:

let nameValue;
let theProduct;

Good naming:

let name;
let product;

Do not use meaningless characters / words to name additional burden of memory

Bad naming:

const users = ["John", "Marco", "Peter"];
users.forEach(u => {
    doSomething();
    doSomethingElse();
    // ...
    // ...
    // ...
    // ...
    // 这里u到底指代什么?
    register(u);
});

Good naming:

const users = ["John", "Marco", "Peter"];
users.forEach(user => {
    doSomething();
    doSomethingElse();
    // ...
    // ...
    // ...
    // ...
    register(user);
});

Under certain circumstances, without adding redundant word combined name. For example, an object called user, then one of the named property directly name, do not need to use usernameup.

Bad naming:

const user = {
  userName: "John",
  userSurname: "Doe",
  userAge: "28"
};

...

user.userName;

Good naming:

const user = {
  name: "John",
  surname: "Doe",
  age: "28"
};

...

user.name;

3. Functions

Please use the full declarative name to name to the function. For example, a function to achieve a certain behavior, then the function name can be a verb or is combined with actors whose behavior is a verb. The name should express to express the behavior of the function.

Bad naming:

function notif(user) {
    // implementation
}

Good naming:

function notifyUser(emailAddress) {
    // implementation
}

Avoid using too many arguments. Preferably only two or less a function's arguments. The fewer parameters, the easier it is to do the test.

Bad use:

function getUsers(fields, fromDate, toDate) {
    // implementation
}

Good use:

function getUsers({ fields, fromDate, toDate }) {
    // implementation
}

getUsers({
    fields: ["name", "surname", "email"],
    fromDate: "2019-01-01",
    toDate: "2019-01-18"
});

Set a default value as a function of the parameter, rather than be assigned is determined by the condition code.

Bad writing:

function createShape(type) {
    const shapeType = type || "cube";
    // ...
}

Good writing:

function createShape(type = "cube") {
    // ...
}

A function should do only one thing. Avoid multiple things stuffed into a function.

Bad writing:

function notifyUsers(users) {
    users.forEach(user => {
        const userRecord = database.lookup(user);
        if (userRecord.isVerified()) {
            notify(user);
        }
    });
}

Good writing:

function notifyVerifiedUsers(users) {
    users.filter(isUserVerified).forEach(notify);
}

function isUserVerified(user) {
    const userRecord = database.lookup(user);
    return userRecord.isVerified();
}

Use Objecg.assignto set the default object value.

Bad writing:

const shapeConfig = {
    type: "cube",
    width: 200,
    height: null
};

function createShape(config) {
    config.type = config.type || "cube";
    config.width = config.width || 250;
    config.height = config.width || 250;
}

createShape(shapeConfig);

Good writing:

const shapeConfig = {
  type: "cube",
  width: 200
  // Exclude the 'height' key
};

function createShape(config) {
  config = Object.assign(
    {
      type: "cube",
      width: 250,
      height: 250
    },
    config
  );

  ...
}

createShape(shapeConfig);

Do not use labels true / false of (flag), because it actually allows the function to do something beyond itself.

Bad writing:

function createFile(name, isPublic) {
    if (isPublic) {
        fs.create(`./public/${name}`);
    } else {
        fs.create(name);
    }
}

Good writing:

function createFile(name) {
    fs.create(name);
}

function createPublicFile(name) {
    createFile(`./public/${name}`);
}

Do not pollute the global. If you need to extend an existing object, do not function defined on the prototype chain of the object. Please use the ES classes and inheritance.

Bad writing:

Array.prototype.myFunc = function myFunc() {
    // implementation
};

Good writing:

class SuperArray extends Array {
    myFunc() {
        // implementation
    }
}

Good coding style can avoid accidentally write code have BUG, just in case, it is recommended to use Fundebug do online real-time monitoring BUG!

4. Analyzing conditions

Conditions to avoid using negative.

Bad writing:

function isUserNotBlocked(user) {
    // implementation
}

if (!isUserNotBlocked(user)) {
    // implementation
}

Good writing:

function isUserBlocked(user) {
    // implementation
}

if (isUserBlocked(user)) {
    // implementation
}

Use short terms. This requirement seems simple, but it is worth reminding.

Bad writing:

if (isValid === true) {
    // do something...
}

if (isValid === false) {
    // do something...
}

Good writing:

if (isValid) {
    // do something...
}

if (!isValid) {
    // do something...
}

If you're sure it's value is not undefinedor is null, I suggest you do so.

Try to avoid using judgment conditions, it is recommended that said polymorphism (polymorphism) or inherited.

Bad writing:

class Car {
    // ...
    getMaximumSpeed() {
        switch (this.type) {
            case "Ford":
                return this.someFactor() + this.anotherFactor();
            case "Mazda":
                return this.someFactor();
            case "McLaren":
                return this.someFactor() - this.anotherFactor();
        }
    }
}

Good writing:

class Car {
    // ...
}

class Ford extends Car {
    // ...
    getMaximumSpeed() {
        return this.someFactor() + this.anotherFactor();
    }
}

class Mazda extends Car {
    // ...
    getMaximumSpeed() {
        return this.someFactor();
    }
}

class McLaren extends Car {
    // ...
    getMaximumSpeed() {
        return this.someFactor() - this.anotherFactor();
    }
}

5. ES 类

The new class is a JavaScript syntax sugar. We recommend the use of classes instead of writing the old-fashioned direct-defined functions.

Bad writing:

const Person = function(name) {
    if (!(this instanceof Person)) {
        throw new Error("Instantiate Person with `new` keyword");
    }

    this.name = name;
};

Person.prototype.sayHello = function sayHello() {
    /**/
};

const Student = function(name, school) {
    if (!(this instanceof Student)) {
        throw new Error("Instantiate Student with `new` keyword");
    }

    Person.call(this, name);
    this.school = school;
};

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.printSchoolName = function printSchoolName() {
    /**/
};

Good writing:

class Person {
    constructor(name) {
        this.name = name;
    }

    sayHello() {
        /* ... */
    }
}

class Student extends Person {
    constructor(name, school) {
        super(name);
        this.school = school;
    }

    printSchoolName() {
        /* ... */
    }
}

Use the function call chain. Like jQuery, Lodash use this mode. You just need to at the end of each function's return this, after the code more concise.

Bad writing:

class Person {
    constructor(name) {
        this.name = name;
    }

    setSurname(surname) {
        this.surname = surname;
    }

    setAge(age) {
        this.age = age;
    }

    save() {
        console.log(this.name, this.surname, this.age);
    }
}

const person = new Person("John");
person.setSurname("Doe");
person.setAge(29);
person.save();

Good writing:

class Person {
    constructor(name) {
        this.name = name;
    }

    setSurname(surname) {
        this.surname = surname;
        // Return this for chaining
        return this;
    }

    setAge(age) {
        this.age = age;
        // Return this for chaining
        return this;
    }

    save() {
        console.log(this.name, this.surname, this.age);
        // Return this for chaining
        return this;
    }
}

const person = new Person("John")
    .setSurname("Doe")
    .setAge(29)
    .save();

6. Other

In general, you can not write duplicate code, can not leave a bunch of functions are no longer used, the code will never be executed (dead code).

In many cases, you might come up with duplicate code. For example, you want to achieve two slightly different functions, they have many of the same place, but as the project deadline is coming, you have to quickly copy paste and then modify slightly modified to achieve.

For dead code, the best thing is that you decide not to use it at the moment to put it deleted. Time in the past for too long, you may even forget why would define it. Figure painting is the image below describes the situation:

About Fundebug

Fundebug focus on JavaScript, applets micro-channel, micro-channel games, Alipay small program, React Native, Node.js and Java applications in real-time online monitoring BUG. Since 2016, two-eleven formally launched, Fundebug handled a total of 1 billion + error event, paying customers have Google, 360, Kingsoft, people network and many other brands. Welcome to Free Trial !

Copyright Notice

Please indicate the author reprinted Fundebug and paper Address:
https://blog.fundebug.com/2019/06/11/javascript-clean-code/

Guess you like

Origin www.cnblogs.com/fundebug/p/javascript-clean-code.html
Recommended