純粋なJavaScript変数

Ryan McDermottの本clean-code-javascriptの翻訳。

目次:



画像

意味のある話し言葉の変数名を使用する


悪い:

const yyyymmdstr = moment().format('YYYY/MM/DD'); 

良い:

 const yearMonthDay = moment().format('YYYY/MM/DD'); 

同じタイプの変数に同じメソッドを使用します


悪い:

 getUserInfo(); getClientData(); getCustomerRecord(); 

良い:

 getUser(); 

名前付きの値を使用する


私たちはこれまでに書くよりも頻繁にコードを読みます。 探しやすい読みやすいコードを書くことが重要です。 名前を検索可能にします。 buddy.jsESLintなどのツールは、名前のない定数を識別するのに役立ちます。

悪い:

 //   86400000? setTimeout(blastOff, 86400000); 

良い:

 //     . const MILLISECONDS_IN_A_DAY = 86400000; setTimeout(blastOff, MILLISECONDS_IN_A_DAY); 

説明変数を使用する


悪い:

 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; saveCityZipCode( address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2] ); 

良い:

 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; const [, city, zipCode] = address.match(cityZipCodeRegex) || []; saveCityZipCode(city, zipCode); 

人名を使用する


明示的は暗黙的よりも優れています。

悪い:

 const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((l) => { doStuff(); doSomeOtherStuff(); // ... // ... // ... //   `l`? dispatch(l); }); 

良い:

 const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((location) => { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch(location); }); 

不要なコンテキストを追加しないでください


クラス/オブジェクト名が何であるかを示している場合は、そのプロパティとメソッドに名前を付けるときにも繰り返してはいけません。

悪い:

 const car = { carMake: 'Honda', carModel: 'Accord', carColor: 'Blue' }; function paintCar(car) { car.carColor = 'Red'; } 

良い:

 const car = { make: 'Honda', model: 'Accord', color: 'Blue' }; function paintCar(car) { car.color = 'Red'; } 

短絡または条件式の代わりにデフォルト条件を使用する


悪い:

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

良い:

 function createMicrobrewery(breweryName = 'Hipster Brew Co.') { // ... } 

Source: https://habr.com/ru/post/J319476/


All Articles