日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

2019年6月26 突然想到的代码优化

發布時間:2023/12/31 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 2019年6月26 突然想到的代码优化 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

(1)傳參使用默認值

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

(2)函數參數( 最好 2 個或更少 )

如果參數超過兩個,建議使用 ES6 的解構語法,不用考慮參數的順序。

// Bad: function createMenu( title, body, buttonText, cancellable ) {// ... } // Good: function createMenu( { title, body, buttonText, cancellable } ) {// ... } createMenu({title: 'Foo',body: 'Bar',buttonText: 'Baz',cancellable: true });

(3)一個方法只做一件事情

這是一條在軟件工程領域流傳久遠的規則。嚴格遵守這條規則會讓你的代碼可讀性更好,也更容易重構。

// 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(); }

(4)刪除重復代碼,合并相似函數

很多時候雖然是同一個功能,但由于一兩個不同點,讓你不得不寫兩個幾乎相同的函數。

// Bad: function showDeveloperList(developers) {developers.forEach((developer) => {const expectedSalary = developer.calculateExpectedSalary();const experience = developer.getExperience();const githubLink = developer.getGithubLink();const data = {expectedSalary,experience,githubLink};render(data);}); } function showManagerList(managers) {managers.forEach((manager) => {const expectedSalary = manager.calculateExpectedSalary();const experience = manager.getExperience();const portfolio = manager.getMBAProjects();const data = {expectedSalary,experience,portfolio};render(data);}); }// Good: function showEmployeeList(employees) {employees.forEach(employee => {const expectedSalary = employee.calculateExpectedSalary();const experience = employee.getExperience();const data = {expectedSalary,experience,};switch(employee.type) {case 'develop':data.githubLink = employee.getGithubLink();breakcase 'manager':data.portfolio = employee.getMBAProjects();break}render(data);}) }

(5)使用 Object.assign 設置默認屬性

// Bad: const 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);// Good: const menuConfig = {title: 'Order',// 不包含 bodybuttonText: 'Send',cancellable: true };function createMenu(config) {config = Object.assign({title: 'Foo',body: 'Bar',buttonText: 'Baz',cancellable: true}, config);// config : {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}// ... }createMenu(menuConfig);

(6) 盡量不要寫全局方法

在 JavaScript 中,永遠不要污染全局,會在生產環境中產生難以預料的 bug。

舉個例子,比如你在 Array.prototype 上新增一個 diff 方法來判斷兩個數組的不同。而你同事也打算做類似的事情,不過他的 diff 方法是用來判斷兩個數組首位元素的不同。很明顯你們方法會產生沖突,遇到這類問題我們可以用 ES2015/ES6 的語法來對 Array 進行擴展。

// Bad: Array.prototype.diff = function diff(comparisonArray) {const hash = new Set(comparisonArray);return this.filter(elem => !hash.has(elem)); };// Good: class SuperArray extends Array {diff(comparisonArray) {const hash = new Set(comparisonArray);return this.filter(elem => !hash.has(elem)); } }

(7) 盡量別用“非”條件句

// Bad: function isDOMNodeNotPresent(node) {// ... } if (!isDOMNodeNotPresent(node)) {// ... }// Good: function isDOMNodePresent(node) {// ... } if (isDOMNodePresent(node)) {// ... }

(8) 盡量不要寫全局方法

在 ES6 之前,沒有類的語法,只能用構造函數的方式模擬類,可讀性非常差。

// Good:// 動物 class Animal {constructor(age) {this.age = age};move() {}; }// 哺乳動物 class Mammal extends Animal{constructor(age, furColor) {super(age);this.furColor = furColor;};liveBirth() {}; }// 人類 class Human extends Mammal{constructor(age, furColor, languageSpoken) {super(age, furColor);this.languageSpoken = languageSpoken;};speak() {}; }

(9) 使用鏈式調用

這種模式相當有用,可以在很多庫中都有使用。它讓你的代碼簡潔優雅。

// Bad: class Car {constructor(make, model, color) {this.make = make;this.model = model;this.color = color;}setMake(make) {this.make = make;}setModel(model) {this.model = model;}setColor(color) {this.color = color;}save() {console.log(this.make, this.model, this.color);} }const car = new Car('Ford','F-150','red'); car.setColor('pink'); car.save();// Good: class Car {constructor(make, model, color) {this.make = make;this.model = model;this.color = color;}setMake(make) {this.make = make;// NOTE: Returning this for chainingreturn this;}setModel(model) {this.model = model;// NOTE: Returning this for chainingreturn this;}setColor(color) {this.color = color;// NOTE: Returning this for chainingreturn this;}save() {console.log(this.make, this.model, this.color);// NOTE: Returning this for chainingreturn this;} }const car = new Car("Ford", "F-150", "red").setColor("pink").save();

(10) 使用 promise 或者 Async/Await 代替回調

// Bad: 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);});// perfect: 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);} }

總結

以上是生活随笔為你收集整理的2019年6月26 突然想到的代码优化的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。