资讯专栏INFORMATION COLUMN

JavaScript 的简洁之道

wudengzan / 1942人阅读

摘要:考虑到函数表示某种行为,函数名称应该是动词或短语,用以说明其背后的意图以及参数的意图。不好的方式好的方式使用条件简写。这可能微不足道,但值得一提。

为了保证可读性,本文采用的音译而非直意。

简介

如果你关注代码本身和代码的编写方式,而不是只关心它是否能工作,那么你写代码是有一定的水准。专业开发人员将为未来的自己和“其他人”编写代码,而不仅仅只编写当前能工作就行的代码。

在此基础上,简洁代码可以定义为自解释的、易于人理解的、易于更改或扩展的代码。

以下列表一些好编写方式,仅供参考,当然,如果你有更好的方式,欢迎留言。

想阅读更多优质文章请猛戳GitHub博客,一年百来篇优质文章等着你!

1. 强类型检查

===代替 ==

</>复制代码

  1. // 如果处理不当,它会极大地影响程序逻辑。这就像,你想向左走,但由于某种原因,你向右走
  2. 0 == false // true
  3. 0 === false // false
  4. 2 == "2" // true
  5. 2 === "2" // false
  6. // 例子
  7. const value = "500";
  8. if (value === 500) {
  9. console.log(value);
  10. // 条件不成立,不会进入
  11. }
  12. if (value === "500") {
  13. console.log(value);
  14. // 条件成立,会进入
  15. }
2.变量

用知名其意的方式为变量命名,通过这种方式,当一个人看到它们时,易于搜索和理解。

不好的方式:

</>复制代码

  1. let daysSLV = 10;
  2. let y = new Date().getFullYear();
  3. let ok;
  4. if (user.age > 30) {
  5. ok = true;
  6. }

好的方式:

</>复制代码

  1. const MAX_AGE = 30;
  2. let daysSinceLastVisit = 10;
  3. let currentYear = new Date().getFullYear();
  4. ...
  5. const isUserOlderThanAllowed = user.age > MAX_AGE;

不要在变量名中添加额外的不需要的单词。

不好的方式:

</>复制代码

  1. let nameValue;
  2. let theProduct;

好的方式:

</>复制代码

  1. let name;
  2. let product;

不要简写变量上下文。

不好的方式:

</>复制代码

  1. const users = ["John", "Marco", "Peter"];
  2. users.forEach(u => {
  3. doSomething();
  4. doSomethingElse();
  5. // ...
  6. // ...
  7. // ...
  8. // ...
  9. // 当上面代码很多的时候 ,这 `u` 是什么鬼
  10. register(u);
  11. });

好的方式:

</>复制代码

  1. const users = ["John", "Marco", "Peter"];
  2. users.forEach(user => {
  3. doSomething();
  4. doSomethingElse();
  5. // ...
  6. // ...
  7. // ...
  8. // ...
  9. register(user);
  10. });

不要添加不必要的上下文。

不好的方式:

</>复制代码

  1. const user = {
  2. userName: "John",
  3. userSurname: "Doe",
  4. userAge: "28"
  5. };
  6. ...
  7. user.userName;

好的方式:

</>复制代码

  1. const user = {
  2. name: "John",
  3. surname: "Doe",
  4. age: "28"
  5. };
  6. ...
  7. user.name;
3. 函数

使用长而具有描述性的名称。 考虑到函数表示某种行为,函数名称应该是动词或短​​语,用以说明其背后的意图以及参数的意图。 函数的名字应该说明他们做了什么。

不好的方式:

</>复制代码

  1. function notif(user) {
  2. // implementation
  3. }

好的方式:

</>复制代码

  1. function notifyUser(emailAddress) {
  2. // implementation
  3. }

避免使用大量参数。 理想情况下,函数应该指定两个或更少的参数。 参数越少,测试函数就越容易,参数多的情况可以使用对象。

不好的方式:

</>复制代码

  1. function getUsers(fields, fromDate, toDate) {
  2. // implementation
  3. }

好的方式:

</>复制代码

  1. function getUsers({ fields, fromDate, toDate }) {
  2. // implementation
  3. }
  4. getUsers({
  5. fields: ["name", "surname", "email"],
  6. fromDate: "2019-01-01",
  7. toDate: "2019-01-18"
  8. });

使用默认参数替代 || 操作

不好的方式:

</>复制代码

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

好的方式:

</>复制代码

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

一个函数应该只做一件事,不要在一个函数中执行多个操作。

不好的方式:

</>复制代码

  1. function notifyUsers(users) {
  2. users.forEach(user => {
  3. const userRecord = database.lookup(user);
  4. if (userRecord.isVerified()) {
  5. notify(user);
  6. }
  7. });
  8. }

好的方式:

</>复制代码

  1. function notifyVerifiedUsers(users) {
  2. users.filter(isUserVerified).forEach(notify);
  3. }
  4. function isUserVerified(user) {
  5. const userRecord = database.lookup(user);
  6. return userRecord.isVerified();
  7. }

使用Object.assign设置对象默认值。

不好的方式:

</>复制代码

  1. const shapeConfig = {
  2. type: "cube",
  3. width: 200,
  4. height: null
  5. };
  6. function createShape(config) {
  7. config.type = config.type || "cube";
  8. config.width = config.width || 250;
  9. config.height = config.height|| 250;
  10. }
  11. createShape(shapeConfig);

好的方式:

</>复制代码

  1. const shapeConfig = {
  2. type: "cube",
  3. width: 200
  4. // Exclude the "height" key
  5. };
  6. function createShape(config) {
  7. config = Object.assign(
  8. {
  9. type: "cube",
  10. width: 250,
  11. height: 250
  12. },
  13. config
  14. );
  15. ...
  16. }
  17. createShape(shapeConfig);

不要使用标志作为参数,因为它们告诉函数做的比它应该做的多。

不好的方式:

</>复制代码

  1. function createFile(name, isPublic) {
  2. if (isPublic) {
  3. fs.create(`./public/${name}`);
  4. } else {
  5. fs.create(name);
  6. }
  7. }

好的方式:

</>复制代码

  1. function createFile(name) {
  2. fs.create(name);
  3. }
  4. function createPublicFile(name) {
  5. createFile(`./public/${name}`);
  6. }

不要污染全局变量。 如果需要扩展现有对象,请使用ES类和继承,而不是在原生对象的原型链上创建函数。

不好的方式:

</>复制代码

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

好的方式:

</>复制代码

  1. class SuperArray extends Array {
  2. myFunc() {
  3. // implementation
  4. }
  5. }
4. 条件

避免使用反面条件。

不好的方式:

</>复制代码

  1. function isUserNotBlocked(user) {
  2. // implementation
  3. }
  4. if (!isUserNotBlocked(user)) {
  5. // implementation
  6. }

好的方式:

</>复制代码

  1. function isUserBlocked(user) {
  2. // implementation
  3. }
  4. if (isUserBlocked(user)) {
  5. // implementation
  6. }

使用条件简写。这可能微不足道,但值得一提。仅对布尔值使用此方法,并且如果你确信该值不会是undefinednull的,则使用此方法。

不好的方式:

</>复制代码

  1. if (isValid === true) {
  2. // do something...
  3. }
  4. if (isValid === false) {
  5. // do something...
  6. }

好的方式:

</>复制代码

  1. if (isValid) {
  2. // do something...
  3. }
  4. if (!isValid) {
  5. // do something...
  6. }

尽可能避免条件句,而是使用多态性和继承。

不好的方式:

</>复制代码

  1. class Car {
  2. // ...
  3. getMaximumSpeed() {
  4. switch (this.type) {
  5. case "Ford":
  6. return this.someFactor() + this.anotherFactor();
  7. case "Mazda":
  8. return this.someFactor();
  9. case "McLaren":
  10. return this.someFactor() - this.anotherFactor();
  11. }
  12. }
  13. }

好的方式:

</>复制代码

  1. class Car {
  2. // ...
  3. }
  4. class Ford extends Car {
  5. // ...
  6. getMaximumSpeed() {
  7. return this.someFactor() + this.anotherFactor();
  8. }
  9. }
  10. class Mazda extends Car {
  11. // ...
  12. getMaximumSpeed() {
  13. return this.someFactor();
  14. }
  15. }
  16. class McLaren extends Car {
  17. // ...
  18. getMaximumSpeed() {
  19. return this.someFactor() - this.anotherFactor();
  20. }
  21. }
5. 类

class 是JavaScript中新的语法糖。一切工作就像以前的原型,只是它现在看起来不同,你应该更喜欢他们比ES5普通功能。

不好的方式:

</>复制代码

  1. const Person = function(name) {
  2. if (!(this instanceof Person)) {
  3. throw new Error("Instantiate Person with `new` keyword");
  4. }
  5. this.name = name;
  6. };
  7. Person.prototype.sayHello = function sayHello() { /**/ };
  8. const Student = function(name, school) {
  9. if (!(this instanceof Student)) {
  10. throw new Error("Instantiate Student with `new` keyword");
  11. }
  12. Person.call(this, name);
  13. this.school = school;
  14. };
  15. Student.prototype = Object.create(Person.prototype);
  16. Student.prototype.constructor = Student;
  17. Student.prototype.printSchoolName = function printSchoolName() { /**/ };

好的方式:

</>复制代码

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. sayHello() {
  6. /* ... */
  7. }
  8. }
  9. class Student extends Person {
  10. constructor(name, school) {
  11. super(name);
  12. this.school = school;
  13. }
  14. printSchoolName() {
  15. /* ... */
  16. }
  17. }

使用链接。许多库(如jQuery和Lodash)都使用这种模式。在类中,只需在每个函数的末尾返回this就可以将更多的该类方法链接到它上。

不好的方式:

</>复制代码

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. setSurname(surname) {
  6. this.surname = surname;
  7. }
  8. setAge(age) {
  9. this.age = age;
  10. }
  11. save() {
  12. console.log(this.name, this.surname, this.age);
  13. }
  14. }
  15. const person = new Person("John");
  16. person.setSurname("Doe");
  17. person.setAge(29);
  18. person.save();

好的方式:

</>复制代码

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. setSurname(surname) {
  6. this.surname = surname;
  7. // Return this for chaining
  8. return this;
  9. }
  10. setAge(age) {
  11. this.age = age;
  12. // Return this for chaining
  13. return this;
  14. }
  15. save() {
  16. console.log(this.name, this.surname, this.age);
  17. // Return this for chaining
  18. return this;
  19. }
  20. }
  21. const person = new Person("John")
  22. .setSurname("Doe")
  23. .setAge(29)
  24. .save();
总结

这只是改进代码的一小部分。一般生活入,这里所说的原则是人们通常不遵守的原则。他们尝试着去做,但出于各种原因,就没有坚持下去。也许在项目开始时,代码是简洁的,但是当要在截止日期前完成时,这些原则常常被忽略,并被转移到“TODO”或“REFACTOR”部分。在这一点上,你的客户更希望您在最后期限之前完成任务,而不是编写简洁的代码。

交流

干货系列文章汇总如下,觉得不错点个Star,欢迎 加群 互相学习。

</>复制代码

  1. https://github.com/qq44924588...

我是小智,公众号「大迁世界」作者,对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!

关注公众号,后台回复福利,即可看到福利,你懂的。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/104589.html

相关文章

  • PHP代码简洁之道——变量部分

    摘要:将代码写的简洁并且易读易懂是每一位优秀的所应该具备的基本功。前几天在上看到这个项目,感觉很有收获,于是在这里记录一下。 将代码写的简洁并且易读易懂是每一位优秀的coder所应该具备的基本功。 前几天在github上看到clean-code-php这个项目,感觉很有收获,于是在这里记录一下。 使用有意义并且可读的变量名称 Bad: $ymdstr = $moment->format(y-...

    mgckid 评论0 收藏0
  • PHP 代码规范简洁之道

    摘要:统一的编码规范编码规范往简单说其实就是三个方面换行空格变量命名放在里面,还有一些附加的地方,比如关键字大小写,语法糖的使用与等的问题。这些都是规范代码的重要手段。推广给你的队友团队项目中,队友的配合对整个代码的规范起着决定性的作用。 1. 统一的编码规范 编码规范往简单说其实就是三个方面: 换行 空格 变量命名 放在 PHP 里面,还有一些附加的地方,比如关键字大小写,语法糖的使用...

    BearyChat 评论0 收藏0
  • PHP代码简洁之道——类和对象部分

    摘要:使用和在中,通过为属性或方法设置和关键字可以实现对属性或方法的可见性控制。你的继承表达了一个对等比如人类是动物的关系,不是包含的关系比如用户具有用户详情你能从基类中复用代码你想通过修改全局类来对所有派生类进行修改。 使用getter和setter 在 PHP 中,通过为属性或方法设置 public, protected 和 private 关键字可以实现对属性或方法的可见性控制。不过,...

    cyixlq 评论0 收藏0
  • 编码之道(一):程序员“圣经“

    摘要:与此类似,理所当然的,我们程序员也会有自己的圣经。这便是程序员的圣经三个原则我认为做为一个程序员,最神圣的就是三个原则,它几乎能完整无误的定义做为一个程序员应该如何去编码。 ...

    Elle 评论0 收藏0
  • PHP代码简洁之道——函数部分

    摘要:超过三个参数会导致参数之间的组合过多,你必须对每个单独的参数测试大量不同的情况。拆分这些函数,可以让代码可重用性更高且更易测试。 函数参数不要超过两个 限制函数的参数数量是非常重要的,因为它使你的函数更容易测试。超过三个参数会导致参数之间的组合过多,你必须对每个单独的参数测试大量不同的情况。 没有参数是最理想的情况,一个或两个参数是可以接受的,三个以上则是应该避免的。这很重要的。如果你...

    crossoverJie 评论0 收藏0

发表评论

0条评论

wudengzan

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<