浅谈JavaScript 代码整洁之道(4)

不好:

function showDeveloperList(developers) {
 developers.forEach(developers => {
 var expectedSalary = developer.calculateExpectedSalary();
 var experience = developer.getExperience();
 var githubLink = developer.getGithubLink();
 var data = {
  expectedSalary: expectedSalary,
  experience: experience,
  githubLink: githubLink
 };

 render(data);
 });
}

function showManagerList(managers) {
 managers.forEach(manager => {
 var expectedSalary = manager.calculateExpectedSalary();
 var experience = manager.getExperience();
 var portfolio = manager.getMBAProjects();
 var data = {
  expectedSalary: expectedSalary,
  experience: experience,
  portfolio: portfolio
 };

 render(data);
 });
}

好:

function showList(employees) {
 employees.forEach(employee => {
 var expectedSalary = employee.calculateExpectedSalary();
 var experience = employee.getExperience();
 var portfolio;

 if (employee.type === 'manager') {
  portfolio = employee.getMBAProjects();
 } else {
  portfolio = employee.getGithubLink();
 }

 var data = {
  expectedSalary: expectedSalary,
  experience: experience,
  portfolio: portfolio
 };

 render(data);
 });
}

使用默认参数代替短路表达式

不好:

function writeForumComment(subject, body) {
 subject = subject || 'No Subject';
 body = body || 'No text';
}

好:

function writeForumComment(subject = 'No subject', body = 'No text') {
 ...
}

用 Object.assign 设置默认对象

不好:

var menuConfig = {
 title: null,
 body: 'Bar',
 buttonText: null,
 cancellable: true
}

function createMenu(config) {
 config.title = config.title || 'Foo'
 config.body = config.body || 'Bar'
 config.buttonText = config.buttonText || 'Baz'
 config.cancellable = config.cancellable === undefined ? config.cancellable : true;

}

createMenu(menuConfig);

好:

var 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 等于: {title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true}
 // ...
}

createMenu(menuConfig);

不要把标记用作函数参数

标记告诉你的用户这个函数做的事情不止一件。但是函数应该只做一件事。如果你的函数中会根据某个布尔参数产生不同的分支,那就拆分这个函数。

不好:

function createFile(name, temp) {
 if (temp) {
 fs.create('./temp/' + name);
 } else {
 fs.create(name);
 }
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/417.html