preface

Today is the second day of my internship in the company. After installing the development software and configuring the development environment, just when I thought I could finally make a big impact, the leader sent me a front-end instruction manual, which contains some documents that new recruits need to read.

Just when I was disappointed and thought it was going to be another hard day, I realized it wasn’t that simple.

When I was an intern in a small company or engaged in some personal project development, I rarely paid attention to the quality of the code, so I wrote a lot of codes that I could understand but could not handle. When I came to this slightly larger company, I realized that the code was not just for me, but for other developers as well.

The simplicity of this code opened up a whole new world to me in a very small amount of space.

The core of code simplicity can be summed up in two sentences: code is self-explanatory (comments should be concise and accurate) and developer friendly (easy to understand, modify, and extend).

At the same time, put yourself in the other developer’s shoes during the development process

"WTF is that?" (What the hell is that?) "WTF did you do here?" What the fuck are you doing? "WTF is this for?" (Why the fuck did you do that?)Copy the code

The following are the main points of code simplicity plus some of my own understanding

Strong type checking

If possible, requests always start with === instead of == for example

0 == false; // true 0 === false; // false 2 == "2"; // true 2 === "2"; // false const value = "500"; If (value === 500) {// Console. log(value) is not executed; } if (value === "500") {console.log(value); }Copy the code

The difference between == and === here’s a brief explanation.

=== compares types first, and values if the types are equal. Returns true if both types and values are equal.

== compares the types first. If the types are not equal, type conversion is performed first

What is said here is not quite complete, the specific difference between == and === and why it is recommended to use ===.

See the difference between == and === in Javascript

Variable naming

This part has always been neglected by me. I believe that many new friends are also like me. Variable naming is not standardized and concise, and it cannot be known by name.

In fact, variable naming as intuitive as possible, easy to find; And it’s easy for other developers to understand.

Bad naming:

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

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

Good naming:

const MAX_AGE = 30; let daysSinceLastVisit = 10; let currentYear = new Date().getFullYear(); . const isUserOlderThanAllowed = user.age > MAX_AGE;Copy the code

Don’t use extra meaningless words to combine names

Bad naming:

let nameValue;
let theProduct;

Copy the code

Good naming:

let name;
let product;
Copy the code

Don’t use meaningless characters/words to add extra memory burden

Bad naming:

users.forEach(u => { doSomething(); doSomethingElse(); / /... / /... / /... / /... // What does u mean? register(u); });Copy the code

Good naming:

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

In some circumstances, redundant words are not added to combine names. For example, if an object is named user, the attribute of one of its names will be name instead of username.

Bad naming:

const user = { userName: "John", userSurname: "Doe", userAge: "28" }; . user.userName;Copy the code

Good naming:

const user = { name: "John", surname: "Doe", age: "28" }; . user.name;Copy the code

These examples are from the original article, and most of them are illustrated by positive and negative comparisons.

Here I recommend a variable named automatic generation site to facilitate your development, development can be in this site input Chinese to get a response to the standard English variable.

CODELF

function

Use full declarative names for functions. For example, if a function implements some behavior, the function name can be either a verb or a verb plus the subject of the action. The name should express the behavior of the function.

Bad naming:

function notif(user) {
    // implementation
}
Copy the code

Good naming:

function notifyUser(emailAddress) {
    // implementation
}
Copy the code

Avoid using too many parameters

Avoid using too many parameters. Ideally, a function has 2 or fewer arguments. The fewer parameters you have, the easier it is to test.

Bad use:

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

Good use:

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

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

Set default values for function parameters

Set default values for function arguments, rather than assigning them by conditional judgment in code.

Bad ways to write:

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

A good way to write:

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

A function should only do one thing

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

Bad ways to write:

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

A good way to write:

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

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

Use objECg.assign to set the default object value

Bad ways to write:

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);
Copy the code

A good way to write:

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);Copy the code

Do not use true/false tags

Don’t use the true/false tag (flag), because it actually makes the function do more than it should. Worst way to write:

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

A good way to write:

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

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

Don’t pollute the whole picture

Don’t pollute the whole situation. If you need to extend an existing object, do not define functions on the object’s prototype chain. Use ES classes and inheritance.

Bad ways to write:

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

A good way to write:

class SuperArray extends Array {
    myFunc() {
        // implementation
    }
}
Copy the code

Judge conditions

Avoid negative conditions

Bad ways to write:

function isUserNotBlocked(user) { // implementation } if (! isUserNotBlocked(user)) { // implementation }Copy the code

A good way to write:

function isUserBlocked(user) {
    // implementation
}

if (isUserBlocked(user)) {
    // implementation
}
Copy the code

Use short conditions

This requirement may seem simple, but it’s worth noting

Bad ways to write:

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

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

A good way to write:

if (isValid) { // do something... } if (! isValid) { // do something... }Copy the code

ES class

Use classes whenever possible

It is recommended to use classes rather than the old-fashioned method of defining functions directly.

Bad ways to write:

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() { /**/ };Copy the code

A good way to write:

class Person { constructor(name) { this.name = name; } sayHello() { /* ... */ } } class Student extends Person { constructor(name, school) { super(name); this.school = school; } printSchoolName() { /* ... * /Copy the code

Use chain calls

Use the function call chain. Like jQuery, Lodash uses this mode. You just return this at the end of each function, and the rest of the code will be much cleaner.

Bad ways to write:

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();
Copy the code

A good way to write:

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();
Copy the code

other

In general, you can’t write duplicate code, leaving behind a bunch of functions that are no longer used, code that will never be executed (dead code).