Translator: Front-end wisdom

Original text: devinduct.com/blogpost/22…

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Introduction to the

If you care about the code and how it’s written, rather than whether it works, then you’re writing code at a certain level. Professional developers will write code for their future selves and “others,” not just code that works today.

On this basis, clean code can be defined as self-explanatory code that is easy to understand and easy to change or extend.

The following list of some good writing methods, only for reference, of course, if you have a better way, welcome to leave a message.

If you want to read more quality articles, please click [GitHub blog][1], a hundred quality articles a year waiting for you!

1. Strong type checking

Replace == with ===

// If not handled properly, it can greatly affect the program logic. It's like, you want to go left, but for some reason, 0 == false // true 0 === false // false 2 == "2" // true 2 === "2" // false // example const value = "500"; if (value === 500) { console.log(value); } if (value === "500") {console.log(value);} if (value === "500") {console.log(value); // if the condition is true, it will enter}Copy the code

2. The variable

Name variables in a way that makes them easy to search for and understand when a person sees them.

Bad ways:

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

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

Good ways:

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

Do not add extra words to variable names that are not needed.

Bad ways:

let nameValue;
let theProduct;
Copy the code

Good ways:

let name;
let product;
Copy the code

Do not abbreviate variable context.

Bad ways:

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

Good ways:

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

Don’t add unnecessary context.

Bad ways:

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

Good ways:

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

3. The function

Use long, descriptive names. Given that a function represents some kind of behavior, the function name should be a verb or phrase that describes the intent behind it and the intent of the parameters. The names of the functions should indicate what they do.

Bad ways:

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

Good ways:

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

Avoid using too many parameters. Ideally, a function should specify two or fewer arguments. The fewer arguments, the easier it is to test the function, and the more arguments you can use objects.

Bad ways:

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

Good ways:

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

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

Use the default parameter substitution | | operation

Bad ways:

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

Good ways:

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

A function should only do one thing; do not perform multiple operations in a function.

Bad ways:

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

Good ways:

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

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

Assign Sets the default Object value using object. assign.

Bad ways:

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

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


createShape(shapeConfig);
Copy the code

Good ways:

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 flags as arguments, because they tell the function to do more than it should.

Bad ways:

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

Good ways:

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

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

Do not pollute global variables. If you need to extend an existing object, use ES classes and inheritance instead of creating functions on a prototype chain of native objects.

Bad ways:

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

Good ways:

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

Conditions of 4.

Avoid negative conditions.

Bad ways:

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

Good ways:

function isUserBlocked(user) {
  // implementation
}

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

Shorthand for conditions of use. It may be trivial, but it’s worth mentioning. Use this method only for Boolean values, and if you are sure that the value will not be undefined or null.

Bad ways:

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

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

Good ways:

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

Avoid conditionals whenever possible and use polymorphism and inheritance instead.

Bad ways:

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

Good ways:

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

Class 5.

Class is the new syntactic sugar in JavaScript. Everything works just like the previous prototype, only it now looks different and you should like them more than ES5 normal features.

Bad ways:

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

Good ways:

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 links. Many libraries, such as jQuery and Lodash, use this pattern. In a class, simply return this at the end of each function to link more of the class’s methods to it.

Bad ways:

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

Good ways:

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

conclusion

This is just a small part of improving the code. In general life, the principles mentioned here are the principles that people don’t usually follow. They try to do it, but for one reason or another, they don’t stick to it. The code may be neat at the start of the project, but when it comes to meeting deadlines, these principles are often ignored and relegated to the “TODO” or “REFACTOR” section. At this point, your client would rather you met a deadline than write clean code.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.