JavaScript代码整洁之道——好代码和坏代码

概述

我们之道作为一个码农,不论其实现如何,功能怎样,写的一手清晰靠谱的代码是其代码功力的体现。好的、清洁的代码可以方便自己以后维护,让你的继任者马上能接手维护它,而不是给你檫屁股,被人戳脊梁骨、被骂垃圾代码。所以,写清洁代码非常重要。

那么什么才是清洁代码的呢?不言而喻,清洁的代码就是可以让人易于人理解、易于更改、方便扩展的代码。写清洁的代码要常扪心自问:

为什么要这样写?

为什么要在这儿写?

为什么不换个写法?

Robert C. Martin在《代码整洁之道》一书中说过:

就算是的坏代码也能运行,但如果代码不干净,也能会让你的开发团队陷入困境。

在本文中,虫虫就给大家讲讲JavaScript代码的整洁知道,全面对比下好的代码和坏的代码的写法。

强类型检查,使用“===”,不用“==”

类型的检查非常重要,使用强类型检查可以帮我理清程序逻辑,如果类型检查松懈了(使用==),有可能使你的逻辑“南辕北撤了”,试看下面的例子:

所以从现在开始就强类型检查,“亡羊补牢,犹未晚也”!

const value = “520”;

if (value === 520) {

  console.log(value);

}

条件不会满足。

if (value === “520”) {

  console.log(value);

}

条件满足。

变量命名

变量的命名要有意义,而不是随意乱起。最好是“望文生义”,一看到变量名就知道是干嘛用的。

望文生义

坏代码:

let daysSLV= 10;

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

 


let ok;

if (user.age > 30) {

  ok = true;

}

好代码:

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

不要给变量添加额外不需要的单词

坏代码:

let nameValue;
let theProduct;

好代码:

let name;

let product;

不要让我们需要从上下文中了解变量的意思

坏代码:

const ans = ["Chongchong", "maomaochong", "bollworm"];

ans.forEach(an => {

  doSomething();

  doSomethingElse();

  // ...

  // 等等,这个u是干嘛用的?

  register(an);

好代码:

const animals = ["Chongchong", "maomaochong", "bollworm"];

animals.forEach(animal => {

  doSomething();

  doSomethingElse();

  // ...

  // ...

  register(animal);

});

不添加多余的上下文

坏代码:

const user = {
  userName: "Chongchong",
  userNameAbb: "CC",
  userAge: "28"
};
...
user.userName;

 

好代码:

const user = {

Name: "Chongchong",
NameAbb: "CC",
  userAge: "28"
};

...
user.userName;

函数

使用长而具有描述性的函数名。

由于函数一般来说表示某种行为,函数名称应该是动词或短​​语,这样可以显示功能以及参数的意义。

坏代码:

function notif(user) {
  // 代码逻辑
}

好代码:

function notifyUser(emailAddress){

  //代码逻辑

}

避免使用大量参数。

理想情况下,函数应该指定两个或更少的参数。参数越少,函数单元测试就越容易。

坏代码:

function getUsers(fields, fromDate, toDate) {
  //代码逻辑

}

好代码:

function getUsers({ fields, fromDate, toDate }) {
  // 码逻辑
}

getUsers({
  fields: ['name', 'surname', 'email'],
  fromDate: '2019-05-22',
  toDate: '2019-05-31'
});

getUsers({

  字段:['name','surname','email'],

  fromDate:'2019-01-01',

  toDate:'2019-01-18'

});

 

使用默认参数,不用条件。

坏代码:

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

好代码:

function createShape(type = "circle") {
  // ...

}

一个函数做一件事。避免在单个函数中执行多个操作,多种逻辑

坏代码:

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

好代码:

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

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

使用Object.assign配置默认对象

坏代码:

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);

function createShape(config){

  config.type = config.type || “立方体”;

  config.width = config.width || 250;

  config.height = config.width || 250;

}

createShape(shapeConfig);

好代码:

const shapeConfig = {

  type: "cube",

  width: 200

};

 

 

function createShape(config) {

  config = Object.assign(

    {

      type: "cube",

      width: 250,

      height: 250

    },

    config

  );

 

  ...

}

 

createShape(shapeConfig);

不要使用标志作为参数。

坏代码:

function createFile(name, isPublic) {

  if (isPublic) {

    fs.create(`./public/${name}`);

  } else {

    fs.create(name);

  }

}

好代码:

function createFile(name) {

  fs.create(name);

}

 

function createPublicFile(name) {

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

}

不要让全局函数污染

如果需要扩展现有对象,请使用ES类和继承,不要在对象原型链上创建函数。

坏代码:

Array.prototype.myFunc = function myFunc() {

  // 代码逻辑

};

好代码:

class SuperArray extends Array {

  myFunc() {

    //代码逻辑

  }

}

条件

不要用负面条件

坏代码:

function isUserNotBlocked(user) {

  //代码逻辑

}

 

if (!isUserNotBlocked(user)) {

  //代码逻辑

}

好代码:

function isUserBlocked(user) {

  //代码逻辑

}

 

if (isUserBlocked(user)) {

  //代码逻辑

}

使用布尔变量直接判断,而不是条件语句

坏代码:

if (isValid === true) {

  //代码逻辑

}

 

if (isValid === false) {

  //代码逻辑

}

好代码:

if (isValid) {

  //代码逻辑

}

 

if (!isValid) {

  //代码逻辑

}

避免使用条件,用多态和继承。

坏代码:

class Car {

  // ...

  getMaximumSpeed() {

    switch (this.type) {

      case "Ford":

        return this.someFactor() + this.anotherFactor();

      case "Benz":

        return this.someFactor();

      case "BYD":

        return this.someFactor() - this.anotherFactor();

    }

  }

}

好代码:

class Car {

  // ...

}

 

class Ford extends Car {

  // ...

  getMaximumSpeed() {

    return this.someFactor() + this.anotherFactor();

  }

}

 

class Benz extends Car {

  // ...

  getMaximumSpeed() {

    return this.someFactor();

  }

}

 

class BYD extends Car {

  // ...

  getMaximumSpeed() {

    return this.someFactor() - this.anotherFactor();

  }

}

ES类

类是JavaScript中的新的语法糖。除了语法不同外,其他都和prototype一样工作。使用ES类可以让你的代码更加简洁清晰。

坏代码:

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

好代码:

class Person {

  constructor(name) {

    this.name = name;

  }

  sayHello() {

    /* ... */

  }

}

 

class Student extends Person {

  constructor(name, school) {

    super(name);

    this.school = school;

  }

  printSchoolName() {

    /* ... */

  }

}

使用方法链接

许多库如jQuery和Lodash都使用该模式。因此,该方法可以让的代码简洁。在主类中,只需在每个函数的末尾返回“this”,就可以将更多的类方法链接到该方法。

坏代码:

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("Chongchong);

person.setSurname("CC");

person.setAge(29);

person.save();

好代码:

class Person {

  constructor(name) {

    this.name = name;

  }

  setSurname(surname) {

    this.surname = surname;

    return this;

  }

  setAge(age) {

    this.age = age;

    return this;

  }

  save() {

    console.log(this.name, this.surname, this.age);

    return this;

  }

}

const person = new Person("Chongchong")

    .setSurname("CC")

    .setAge(29)

.save();

其他

通常情况下,尽量不要写不要重复代码,不要写不使用的函数和死代码。

出于历史原因,可能会遇到重复的代码。例如,有两段你略有不同的低吗,但是又很多共同之处逻辑,为省事或者赶工期,导致你复制了大段代码,略做小改然后使用了。针对这种代码,后期一定要及早抽象出相同逻辑部分删除重复代码越早越好,不要欠死账,不然后越积越多就不好处理了。

关于死代码,码如其名。就是啥事不干,删了可能引入错误,这和上面的一样处理,及早处理,不用了就早处理,早删除。

结论

上面只是代码整洁的部分原理,而且个别条款也可能需要商榷。这些大部分理论来源于《代码整洁之道》这本书。有什么建议意见请回复,一起学习讨论。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注