フォーマット
フォーマットは主観的な問題です。ここで説明する多くのルールと同様に、厳格に従うべき絶対的な基準はありません。重要な点は、フォーマットを巡って議論しないことです。この作業を自動化する多数のツールが存在します。それらを活用してください。エンジニアがフォーマットについて議論するのは時間とコストの無駄です。
自動フォーマットの対象外となる要素(インデント、タブとスペースの選択、ダブルクォート vs. シングルクォートの使い分けなど)については、ここで説明するガイドラインを参考にしてください。
大文字表記の一貫性
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();