Skip to content

代码格式

代码格式具有主观性。本文所述的许多规则中,没有必须绝对遵守的条目。核心原则是:不要争论格式问题。已有大量自动化工具可解决这一问题,因此直接选用工具即可。工程师团队若陷入格式争议,这会浪费时间和金钱。

针对无法自动格式化的内容(缩进方式、制表符与空格选择、引号类型等),可以参考以下指导原则。

保持大小写统一性

「JavaScript」作为无类型语言,命名的大小写规范能有效传递变量、函数等要素的类型信息。相关规则虽具主观性,但各团队可自行制定标准。关键要求在于选定方案后,所有成员应保持贯彻一致性。

不良做法:

javascript
const DAYS_IN_WEEK = 7;
const daysInMonth = 30;

const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const Artists = ["ACDC", "Led Zeppelin", "The Beatles"];

function eraseDatabase() {}
function restore_database() {}

class animal {}
class Alpaca {}

推荐做法:

javascript
const DAYS_IN_WEEK = 7;
const DAYS_IN_MONTH = 30;

const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"];

function eraseDatabase() {}
function restoreDatabase() {}

class Animal {}
class Alpaca {}

函数调用者与被调用者应保持相邻

当存在函数调用关系时,建议在源码中保持调用者与被调用函数的垂直邻近性。理想情况是将调用者置于被调用函数的上方。我们习惯像阅读普通文本那样从上至下阅读代码,因此应确保代码结构符合这种自然阅读顺序。

不良做法:

javascript
class PerformanceReview {
  constructor(employee) {
    this.employee = employee;
  }

  lookupPeers() {
    return db.lookup(this.employee, "peers");
  }

  lookupManager() {
    return db.lookup(this.employee, "manager");
  }

  getPeerReviews() {
    const peers = this.lookupPeers();
    // ...
  }

  perfReview() {
    this.getPeerReviews();
    this.getManagerReview();
    this.getSelfReview();
  }

  getManagerReview() {
    const manager = this.lookupManager();
  }

  getSelfReview() {
    // ...
  }
}

const review = new PerformanceReview(employee);
review.perfReview();

推荐做法:

javascript
class PerformanceReview {
  constructor(employee) {
    this.employee = employee;
  }

  perfReview() {
    this.getPeerReviews();
    this.getManagerReview();
    this.getSelfReview();
  }

  getPeerReviews() {
    const peers = this.lookupPeers();
    // ...
  }

  lookupPeers() {
    return db.lookup(this.employee, "peers");
  }

  getManagerReview() {
    const manager = this.lookupManager();
  }

  lookupManager() {
    return db.lookup(this.employee, "manager");
  }

  getSelfReview() {
    // ...
  }
}

const review = new PerformanceReview(employee);
review.perfReview();