js基石之—易讀、易復用、易重構的 JavaScript 程式碼規範

易讀、易復用、易重構的 JavaScript 程式碼規範

1.變數命名規範有意義

Bad:

const yyyymmdstr = moment().format("YYYY/MM/DD");
Good:

const currentDate = moment().format("YYYY/MM/DD");

2. 給變數定義名字

Bad:

// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);
Good:

// Declare them as capitalized named constants.
const MILLISECONDS_IN_A_DAY = 86_400_000;

setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

3.函數的變數定義初始值

Bad:

function createMicrobrewery(name) {
  const breweryName = name || "Hipster Brew Co.";
  // ...
}
Good:

function createMicrobrewery(name = "Hipster Brew Co.") {
  // ...
}


4.函數的形參過多時候,用對象代替多個參數

Bad:

function createMenu(title, body, buttonText, cancellable) {
  // ...
}

createMenu("Foo", "Bar", "Baz", true);
Good:

function createMenu({ title, body, buttonText, cancellable }) {
  // ...
}

createMenu({
  title: "Foo",
  body: "Bar",
  buttonText: "Baz",
  cancellable: true
});

5.函數應該只做一件事情

Bad:

function emailClients(clients) {
  clients.forEach(client => {
    const clientRecord = database.lookup(client);
    if (clientRecord.isActive()) {
      email(client);
    }
  });
}
Good:

function emailActiveClients(clients) {
  clients.filter(isActiveClient).forEach(email);
}

function isActiveClient(client) {
  const clientRecord = database.lookup(client);
  return clientRecord.isActive();
}

6.函數名應該告訴這個函數是用來幹嘛的

Bad:

function addToDate(date, month) {
  // ...
}

const date = new Date();

// It's hard to tell from the function name what is added
addToDate(date, 1);
Good:

function addMonthToDate(month, date) {
  // ...
}

const date = new Date();
addMonthToDate(1, date)

7.定義對象使用深拷貝

Good:

const menuConfig = {
  title: "Order",
  // User did not include 'body' key
  buttonText: "Send",
  cancellable: true
};

function createMenu(config) {
  config = Object.assign(
    {
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
    },
    config
  );

  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  // ...
}

createMenu(menuConfig);

參考地址來源 ://github.com/ryanmcdermott/clean-code-javascript