当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Clean Code之JavaScript代码示例

Clean Code之JavaScript代码示例

2019年06月12日  | 移动技术网IT编程  | 我要评论

译者按: 简洁的代码可以避免写出过多的bug。

本文采用意译,版权归原作者所有

引文

作为一个开发者,如果你关心代码质量,除了需要认真测试代码能否正确执行以外,还要注重代码的整洁(clean code)。一个专业的开发者会从将来自己或则他人方便维护的角度考虑如何写代码,而不仅仅是机器能够读懂。你写的任何代码有很大几率会被再次重构,希望未来重构代码的那个人不会觉得这是一场灾难。

代码的简洁之道可以被理解为:代码自我解释(且注释少),开发者友好(易于理解,修改和扩展)。

想想之前阅读别人的代码的时候,说过多少次下面的话?

"wtf is that?"

"wtf did you do here?"

"wtf is this for?"

下面这张图很形象地描述了这个情况:

img

《clean code》的作者robert c. martin (uncle bob) 说过这样的话.

虽然烂代码可以运行,但是它不够整洁,它会把整个开发团队给整跪了

本文主要讲 javascript 代码的整洁之道。

1. 强类型检查

建议使用 === 而不是 == 来判断是否相等

// 如果没有妥善处理的话,可能会出现和预想不一样的结果
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. 变量命名

变量命名尽量直观易懂,方便查找;而且其他开发者也容易理解。

不好的命名方式:

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 users = ["john", "marco", "peter"];
users.foreach(u => {
    dosomething();
    dosomethingelse();
    // ...
    // ...
    // ...
    // ...
    // 这里u到底指代什么?
    register(u);
});

好的命名方式:

const users = ["john", "marco", "peter"];
users.foreach(user => {
    dosomething();
    dosomethingelse();
    // ...
    // ...
    // ...
    // ...
    register(user);
});

在某些环境下,不用添加冗余的单词来组合命名。比如一个对象叫user,那么其中的一个名字的属性直接用name,不需要再使用username了。

坏的命名方式:

const user = {
  username: "john",
  usersurname: "doe",
  userage: "28"
};

...

user.username;

好的命名方式:

const user = {
  name: "john",
  surname: "doe",
  age: "28"
};

...

user.name;

3. 函数

请使用完整的声明式的名字来给函数命名。比如一个函数实现了某个行为,那么函数名可以是一个动词或则一个动词加上其行为的被作用者。名字就应该表达出函数要表达的行为。

坏的命名方式:

function notif(user) {
    // implementation
}

好的命名方式:

function notifyuser(emailaddress) {
    // implementation
}

避免使用过多参数。最好一个函数只有 2 个甚至更少的参数。参数越少,越容易做测试。

坏的使用方式:

function getusers(fields, fromdate, todate) {
    // implementation
}

好的使用方式:

function getusers({ fields, fromdate, todate }) {
    // implementation
}

getusers({
    fields: ["name", "surname", "email"],
    fromdate: "2019-01-01",
    todate: "2019-01-18"
});

为函数参数设置默认值,而不是在代码中通过条件判断来赋值。

坏的写法:

function createshape(type) {
    const shapetype = type || "cube";
    // ...
}

好的写法:

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

一个函数应该只做一件事情。避免将多个事情塞到一个函数中。

坏的写法:

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

使用objecg.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);

好的写法:

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

不要使用 true/false 的标签(flag),因为它实际上让函数做了超出它本身的事情。

坏的写法:

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

好的写法:

class superarray extends array {
    myfunc() {
        // implementation
    }
}

好的代码风格可以避免不小心写出有bug的代码,以防万一,推荐使用fundebug做线上实时bug监控!

4. 判断条件

避免使用否定的条件。

坏的写法:

function isusernotblocked(user) {
    // implementation
}

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

好的写法:

function isuserblocked(user) {
    // implementation
}

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

使用简短的条件。这个要求看上去简单,但是值得提醒。

坏的写法:

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

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

好的写法:

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

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

如果你很确定它的值不是undefined或则null,我建议你这么做。

尽量避免使用判断条件,推荐说那个多态(polymorphism)或则继承。

坏的写法:

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

好的写法:

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 类

类是 javascript 新推出的语法糖。建议使用类而不是用老式的直接定义函数的写法。

坏的写法:

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("john");
person.setsurname("doe");
person.setage(29);
person.save();

好的写法:

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. 其它

总的来说,你不能写重复代码,不能留下一堆不再使用的函数,永远不会执行的代码(死代码)。

在很多情况下,你可能搞出重复代码。比如你要实现两个略微不同的功能,他们有很多相通的地方,但是由于项目截止时间快到了,你不得不快速复制黏贴再稍微修改修改来实现。

对于死代码,最好的做法就是你决定不再使用它的那一刻就把它删掉。时间过去太久,你甚至会忘记自己当初为什么定义它。下面这幅图很形象地描述了这个情况:

关于fundebug

fundebug专注于javascript、微信小程序、微信小游戏、支付宝小程序、react native、node.js和java线上应用实时bug监控。 自从2016年双十一正式上线,fundebug累计处理了10亿+错误事件,付费客户有google、360、金山软件、百姓网等众多品牌企业。欢迎大家!

版权声明

转载时请注明作者fundebug以及本文地址:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网