浅谈JavaScript 代码简洁之道(11)

测试

随着项目变得越来越庞大,时间线拉长,有的老代码可能半年都没碰过,如果此时上线,你有信心这部分代码能正常工作吗?测试的覆盖率和你的信心是成正比的。

PS: 如果你发现你的代码很难被测试,那么你应该优化你的代码了。

单一化

Bad:

import assert from 'assert';

describe('MakeMomentJSGreatAgain', () => {
 it('handles date boundaries', () => {
 let date;

 date = new MakeMomentJSGreatAgain('1/1/2015');
 date.addDays(30);
 assert.equal('1/31/2015', date);

 date = new MakeMomentJSGreatAgain('2/1/2016');
 date.addDays(28);
 assert.equal('02/29/2016', date);

 date = new MakeMomentJSGreatAgain('2/1/2015');
 date.addDays(28);
 assert.equal('03/01/2015', date);
 });
});

Good:

import assert from 'assert';

describe('MakeMomentJSGreatAgain', () => {
 it('handles 30-day months', () => {
 const date = new MakeMomentJSGreatAgain('1/1/2015');
 date.addDays(30);
 assert.equal('1/31/2015', date);
 });

 it('handles leap year', () => {
 const date = new MakeMomentJSGreatAgain('2/1/2016');
 date.addDays(28);
 assert.equal('02/29/2016', date);
 });

 it('handles non-leap year', () => {
 const date = new MakeMomentJSGreatAgain('2/1/2015');
 date.addDays(28);
 assert.equal('03/01/2015', date);
 });
});

异步

不再使用回调

不会有人愿意去看嵌套回调的代码,用 Promises 替代回调吧。

Bad:

import { get } from 'request';
import { writeFile } from 'fs';

get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => {
 if (requestErr) {
 console.error(requestErr);
 } else {
 writeFile('article.html', response.body, (writeErr) => {
  if (writeErr) {
  console.error(writeErr);
  } else {
  console.log('File written');
  }
 });
 }
});

Good:

get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
 .then((response) => {
 return writeFile('article.html', response);
 })
 .then(() => {
 console.log('File written');
 })
 .catch((err) => {
 console.error(err);
 });

Async/Await 比起 Promises 更简洁

Bad:

import { get } from 'request-promise';
import { writeFile } from 'fs-promise';

get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
 .then((response) => {
 return writeFile('article.html', response);
 })
 .then(() => {
 console.log('File written');
 })
 .catch((err) => {
 console.error(err);
 });

Good:

import { get } from 'request-promise';
import { writeFile } from 'fs-promise';

async function getCleanCodeArticle() {
 try {
 const response = await get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
 await writeFile('article.html', response);
 console.log('File written');
 } catch(err) {
 console.error(err);
 }
}
      

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

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