diff --git a/README.md b/README.md index 056dbac6..219381d6 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,92 @@ +ต้นฉบับจาก https://github.com/ryanmcdermott/clean-code-javascript + # clean-code-javascript -## Table of Contents +## สารบัญ 1. [Introduction](#introduction) 2. [Variables](#variables) 3. [Functions](#functions) 4. [Objects and Data Structures](#objects-and-data-structures) 5. [Classes](#classes) - 6. [Testing](#testing) - 7. [Concurrency](#concurrency) - 8. [Error Handling](#error-handling) - 9. [Formatting](#formatting) - 10. [Comments](#comments) - 11. [Translation](#translation) + 6. [SOLID](#solid) + 7. [Testing](#testing) + 8. [Concurrency](#concurrency) + 9. [Error Handling](#error-handling) + 10. [Formatting](#formatting) + 11. [Comments](#comments) + 12. [Translation](#translation) ## Introduction ![Humorous image of software quality estimation as a count of how many expletives you shout when reading code](http://www.osnews.com/images/comics/wtfm.jpg) -Software engineering principles, from Robert C. Martin's book -[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), -adapted for JavaScript. This is not a style guide. It's a guide to producing -readable, reusable, and refactorable software in JavaScript. +หลักการในการพัฒนาซอฟท์แวร์ซึ่งนำมาจากหนังสือของ Robert C. Martin ที่ชื่อว่า +[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) +โดยมีการปรับแต่งให้อยู่ในรูปของ JavaScript +นี่ไม่ใช่สไตล์ไกด์ แต่เป็นไกด์เพื่อสร้างโค้ด JavaScript +ที่อ่านง่าย(readable) ใช้ซ้ำได้(reusable) และปรับโครงสร้างได้(refactorable) -Not every principle herein has to be strictly followed, and even fewer will be -universally agreed upon. These are guidelines and nothing more, but they are -ones codified over many years of collective experience by the authors of -*Clean Code*. +ทุกๆหลักการในที่นี้ไม่จำเป็นต้องทำตามอย่างเคร่งครัด และมีเพียงบางหลักการเท่านั้นที่เป็นที่ยอมรับอย่างเป็นสากล +นี่เป็นเพียงไกด์ไลน์ที่เกิดจากประสบการณ์หลายปีของผู้เขียนหนังสือ Clean Code -Our craft of software engineering is just a bit over 50 years old, and we are -still learning a lot. When software architecture is as old as architecture -itself, maybe then we will have harder rules to follow. For now, let these -guidelines serve as a touchstone by which to assess the quality of the -JavaScript code that you and your team produce. +การพัฒนาซอฟท์แวร์เพิ่งผ่านมาแค่ 50 กว่าปีเท่านั้น และเรายังคงต้องเรียนรู้อีกมาก +เมื่อสถาปัตยกรรมการพัฒนาซอฟท์แวร์เก่าแก่พอ เมื่อนั้นเราอาจจะมีกฏที่เข้มงวดขึ้นให้ต้องปฏิบัติตาม +แต่ตอนนี้ ให้ไกด์ไลน์นี้เป็นเหมือนสิ่งที่ใช้ตรวจสอบคุณภาพของโค้ด JavaScript ที่คุณและทีมของคุณสร้างขึ้น -One more thing: knowing these won't immediately make you a better software -developer, and working with them for many years doesn't mean you won't make -mistakes. Every piece of code starts as a first draft, like wet clay getting -shaped into its final form. Finally, we chisel away the imperfections when -we review it with our peers. Don't beat yourself up for first drafts that need -improvement. Beat up the code instead! +อีกเรื่องหนึ่ง การทำตามหลักการนี้ไม่ได้ช่วยให้คุณเป็น software developer ที่ดีขึ้นได้ทันที +และการอยู่กับมันหลายปีไม่ได้หมายความว่าคุณจะไม่ทำผิดพลาด +ทุกๆส่วนของโค้ดเริ่มจากฉบับร่าง เหมือนกับการขึ้นรูปปั้นดินเหนียว +ในท้ายที่สุดแล้ว เราจะกำจัดส่วนที่ไม่สมบูรณ์ออกไป อย่าเพิ่งโทษตัวเองกับแบบร่างแรกที่ต้องการการปรับปรุง +แต่จงจัดการกับโค้ดซะ! -## **Variables** -### Use meaningful and pronounceable variable names +## Variables +### ใช้ชื่อตัวแปรที่สือความหมายและอ่านออกเสียงได้ -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript const yyyymmdstr = moment().format('YYYY/MM/DD'); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript const currentDate = moment().format('YYYY/MM/DD'); ``` **[⬆ back to top](#table-of-contents)** -### Use the same vocabulary for the same type of variable +### ใช้คำเดียวกันสำหรับตัวแปรที่ใช้งานแบบเดียวกัน -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript getUserInfo(); getClientData(); getCustomerRecord(); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript getUser(); ``` **[⬆ back to top](#table-of-contents)** -### Use searchable names -We will read more code than we will ever write. It's important that the code we -do write is readable and searchable. By *not* naming variables that end up -being meaningful for understanding our program, we hurt our readers. -Make your names searchable. Tools like -[buddy.js](https://github.com/danielstjules/buddy.js) and +### ใช้ชื่อที่สามารถค้นหาได้ +เรามักจะต้องอ่านโค้ดที่เราเขียนไว้ จึงเป็นเรื่องสำคัญมากที่โค้ดที่เราเขียนต้องสามารถอ่านได้และค้นหาได้ง่าย +โดยเราจะต้องไม่ตั้งชื่อตัวแปรที่ทำร้ายคนที่จะมาอ่านโค้ดต่อจากเรา +ตั้งชื่อให้สามารถค้นหาได้ เครื่องมืออย่าง +[buddy.js](https://github.com/danielstjules/buddy.js) และ [ESLint](https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md) -can help identify unnamed constants. +ช่วยให้เราค้นหาค่าคงที่ที่ไม่ได้ถูกตั้งชื่อได้ -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript -// What the heck is 86400000 for? +// ตัวเลข 86400000 สื่อถึงอะไร? setTimeout(blastOff, 86400000); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript -// Declare them as capitalized `const` globals. +// ประกาศตัวแปรด้วยตัวพิมพ์ใหญ่เป็นค่าคงที่ const MILLISECONDS_IN_A_DAY = 86400000; setTimeout(blastOff, MILLISECONDS_IN_A_DAY); @@ -96,15 +94,15 @@ setTimeout(blastOff, MILLISECONDS_IN_A_DAY); ``` **[⬆ back to top](#table-of-contents)** -### Use explanatory variables -**Bad:** +### ใช้ตัวแปรเพื่อเป็นการอธิบาย code +**ตัวอย่างที่ไม่ดี:** ```javascript const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; @@ -113,10 +111,10 @@ saveCityZipCode(city, zipCode); ``` **[⬆ back to top](#table-of-contents)** -### Avoid Mental Mapping -Explicit is better than implicit. +### หลีกเลี่ยงการตั้งชื่อที่มีแค่เราที่เข้าใจ +ตั้งชื่อตัวแปรให้ชัดเจนดีกว่าต้องมาคาดเดาทีหลัง -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((l) => { @@ -125,12 +123,12 @@ locations.forEach((l) => { // ... // ... // ... - // Wait, what is `l` for again? + // พอมาถึงบรรทัดนี้เราก็จะลืมไปแล้วว่าตัวแปร l คืออะไร dispatch(l); }); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((location) => { @@ -144,11 +142,10 @@ locations.forEach((location) => { ``` **[⬆ back to top](#table-of-contents)** -### Don't add unneeded context -If your class/object name tells you something, don't repeat that in your -variable name. +### อย่าใส่สิ่งที่ไม่จำเป็นลงใน code +ถ้าชื่อ class/object บอกอยู่แล้วว่าสื่อถึงอะไร ไม่จำเป็นต้องใส่อีกในชื่อตัวแปร -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript const Car = { carMake: 'Honda', @@ -161,7 +158,7 @@ function paintCar(car) { } ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript const Car = { make: 'Honda', @@ -175,9 +172,12 @@ function paintCar(car) { ``` **[⬆ back to top](#table-of-contents)** -### Use default arguments instead of short circuiting or conditionals +### ใช้ Default arguments แทนการ Short circuit หรือเช็คเงื่อนไข +การใช้ Default arguments ทำให้โค้ดดู "สะอาด" กว่าการใช้ Short circuit +โปรดระวังในการใช้ด้วยเพราะ Default arguments จะกำหนดค่าให้เฉพาะ arguments ที่เป็น undefined เท่านั้น +ค่าที่เป็น `''`, `""`, `false`, `null`, `0`, และ `NaN` จะไม่ถูกแทนค่าด้วย Default value -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript function createMicrobrewery(name) { const breweryName = name || 'Hipster Brew Co.'; @@ -186,9 +186,9 @@ function createMicrobrewery(name) { ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript -function createMicrobrewery(breweryName = 'Hipster Brew Co.') { +function createMicrobrewery(name = 'Hipster Brew Co.') { // ... } @@ -196,42 +196,34 @@ function createMicrobrewery(breweryName = 'Hipster Brew Co.') { **[⬆ back to top](#table-of-contents)** ## **Functions** -### Function arguments (2 or fewer ideally) -Limiting the amount of function parameters is incredibly important because it -makes testing your function easier. Having more than three leads to a -combinatorial explosion where you have to test tons of different cases with -each separate argument. - -One or two arguments is the ideal case, and three should be avoided if possible. -Anything more than that should be consolidated. Usually, if you have -more than two arguments then your function is trying to do too much. In cases -where it's not, most of the time a higher-level object will suffice as an -argument. - -Since JavaScript allows you to make objects on the fly, without a lot of class -boilerplate, you can use an object if you are finding yourself needing a -lot of arguments. - -To make it obvious what properties the function expects, you can use the es6 -destructuring syntax. This has a few advantages: - -1. When someone looks at the function signature, it's immediately clear what -properties are being used. -2. Destructuring also clones the specified primitive values of the argument -object passed into the function. This can help prevent side effects. Note: -objects and arrays that are destructured from the argument object are NOT -cloned. -3. Linters can warn you about unused properties, which would be impossible -without destructuring. +### Function arguments (มีเพียง 2 หรือน้อยกว่ายิ่งดี) +จำกัดจำนวน function parameter เป็นสิ่งที่สำคัญเพราะจะทำให้การ test function ง่ายขึ้น +การมี parameter มากกว่า 3 จะทำให้ต้อง test ลำบาก เพราะต้องเขียนครอบคลุมหลาย test case -**Bad:** +การมีเพียง 1 หรือ 2 argument เป็นสิ่งที่ดี ส่วนการมี 3 argument เป็นสิ่งที่ควรหลีกเลี่ยง +และไม่ควรมีมากกว่านั้น ปกติถ้ามีมากกว่า 2 argument แสดงว่า function นั้นพยายามทำหลายอย่างมากเกินไป +ถ้าไม่ ก็ควรใช้เป็นตัวแปรประเภท object แทน + +เพราะภาษา javascript สามารถสร้าง object ได้ง่ายโดยไม่ต้องเขียน class boilerplate +คุณสามารถใช้ object แทน argument หลายตัวแทน + +คุณสามารถใช้ destrcuturing ของ ES2015/ES6 เพื่อแสดงให้ชัดเจนว่า function ต้องการ property ใดบ้าง +ซึ่งการทำแบบนี้มีข้อดีดังนี้ + +1. เมื่อมีคนดูที่ function จะสามารถรู้ได้ทันทีว่าต้องการ property ใดบ้าง +2. การใช้ destructuring จะมีการ clone primitive value ของ argument +ที่ถูกส่งเข้ามาใน function ทำให้ไม่เกิด side effect +ยกเว้นตัวแปรประเภท object และ array จะไม่ถูก clone +3. linter สามารถเตือนได้ว่ามี property ใดบ้างที่ไม่ถูกใช้ ซึ่งจะทำไม่ได้หากไม่ใช้ destructuring + +**ตัวอย่างที่ไม่ดี:** ```javascript function createMenu(title, body, buttonText, cancellable) { // ... } ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript function createMenu({ title, body, buttonText, cancellable }) { // ... @@ -247,14 +239,11 @@ createMenu({ **[⬆ back to top](#table-of-contents)** -### Functions should do one thing -This is by far the most important rule in software engineering. When functions -do more than one thing, they are harder to compose, test, and reason about. -When you can isolate a function to just one action, they can be refactored -easily and your code will read much cleaner. If you take nothing else away from -this guide other than this, you'll be ahead of many developers. +### Functions ควรทำแค่สิ่งเดียว +function ควรทำเพียงแค่สิ่งเดียวนั่นถือเป็นกฏที่สำคัญของ software engineering +เมื่อ function เริ่มทำมากกว่าหนึ่งอย่างจะทำให้ยากแก่การสร้าง ทดสอบ function นั้นๆ ถ้า function ทำแค่เพียงสิ่งเดียวแล้ว เราจะสามารถ refactor ได้ง่าย และ code ยังอ่านง่ายอีกด้วย -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript function emailClients(clients) { clients.forEach((client) => { @@ -266,24 +255,24 @@ function emailClients(clients) { } ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript -function emailClients(clients) { +function emailActiveClients(clients) { clients - .filter(isClientActive) + .filter(isActiveClient) .forEach(email); } -function isClientActive(client) { +function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); } ``` **[⬆ back to top](#table-of-contents)** -### Function names should say what they do +### ชื่อ function ควรสื่อถึงสิ่งที่ function นั้นทำ -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript function addToDate(date, month) { // ... @@ -291,11 +280,11 @@ function addToDate(date, month) { const date = new Date(); -// It's hard to to tell from the function name what is added +// เราไม่สามารถบอกจากชื่อ function ได้ว่าอะไรถูก add addToDate(date, 1); ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript function addMonthToDate(month, date) { // ... @@ -306,12 +295,13 @@ addMonthToDate(1, date); ``` **[⬆ back to top](#table-of-contents)** -### Functions should only be one level of abstraction +### Function ควร abstract เพียงแค่ชั้นเดียว +function ไม่ควรทำหลายๆอย่างภายใน function เดียว ควรแยกสิ่งที่ทำอย่างอื่นออกมาเป็นอีก function ต่างหาก When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing. -**Bad:** +**ตัวอย่างที่ไม่ดี:** ```javascript function parseBetterJSAlternative(code) { const REGEXES = [ @@ -337,8 +327,16 @@ function parseBetterJSAlternative(code) { } ``` -**Good:** +**ตัวอย่างที่ดี:** ```javascript +function parseBetterJSAlternative(code) { + const tokens = tokenize(code); + const ast = lexer(tokens); + ast.forEach((node) => { + // parse... + }); +} + function tokenize(code) { const REGEXES = [ // ... @@ -363,26 +361,20 @@ function lexer(tokens) { return ast; } - -function parseBetterJSAlternative(code) { - const tokens = tokenize(code); - const ast = lexer(tokens); - ast.forEach((node) => { - // parse... - }); -} ``` **[⬆ back to top](#table-of-contents)** -### Remove duplicate code +### ลดโค้ดที่ซ้ำซ้อนออก Do your absolute best to avoid duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic. +ควรพยายามหลีกเลี่ยงการเขียนโค้ดซ้ำซ้อน การเขียนโค้ดซ้ำซ้อนเป็นสิ่งที่ไม่ดีเพราะมันหมายถึงเราต้องทำการแก้ไขมากกว่า 1 ที่ถ้ามีการเปลี่ยนโลจิคการทำงาน Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. If you only have one list, there's only one place to update! +ลองจินตนาการว่าถ้าเป็นร้านอาหารแล้วคุณต้องทำการตรวจเช็ค ไม่ว่าจะเป็นมะเขือเทศ หัวหอม กะเทียม เครื่องเทศ แล้วคุณต้องคอยอัพเดททุกๆครั้งที่มีการเซิฟอาหาร ถ้าคุณมีลิสต์รายการหลายๆลิสต์ คุณต้องอัพเดททุกๆลิสต์ แต่ถ้ามีแค่ลิสต์เดียวคุณก็แค่อัพเดทแค่เพียงที่เดียวเท่านั้น Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you @@ -431,23 +423,25 @@ function showManagerList(managers) { **Good:** ```javascript -function showList(employees) { +function showEmployeeList(employees) { employees.forEach((employee) => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); - let portfolio = employee.getGithubLink(); - - if (employee.type === 'manager') { - portfolio = employee.getMBAProjects(); - } - const data = { expectedSalary, - experience, - portfolio + experience }; + switch (employee.type) { + case 'manager': + data.portfolio = employee.getMBAProjects(); + break; + case 'developer': + data.githubLink = employee.getGithubLink(); + break; + } + render(data); }); } @@ -469,7 +463,7 @@ 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; + config.cancellable = config.cancellable !== undefined ? config.cancellable : true; } createMenu(menuConfig); @@ -574,7 +568,7 @@ console.log(newName); // ['Ryan', 'McDermott']; ### Avoid Side Effects (part 2) In JavaScript, primitives are passed by value and objects/arrays are passed by -reference. In the case of objects and arrays, if our function makes a change +reference. In the case of objects and arrays, if your function makes a change in a shopping cart array, for example, by adding an item to purchase, then any other function that uses that `cart` array will be affected by this addition. That may be great, however it can be bad too. Let's imagine a bad @@ -596,7 +590,7 @@ holding onto a reference of the shopping cart will be affected by any changes. Two caveats to mention to this approach: 1. There might be cases where you actually want to modify the input object, -but when you adopt this programming practice you will find that those case +but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects! 2. Cloning big objects can be very expensive in terms of performance. Luckily, @@ -615,7 +609,7 @@ const addItemToCart = (cart, item) => { **Good:** ```javascript const addItemToCart = (cart, item) => { - return [...cart, { item, date : Date.now() }]; + return [...cart, { item, date: Date.now() }]; }; ``` @@ -653,7 +647,7 @@ class SuperArray extends Array { ### Favor functional programming over imperative programming JavaScript isn't a functional language in the way that Haskell is, but it has -a functional flavor to it. Functional languages are cleaner and easier to test. +a functional flavor to it. Functional languages can be cleaner and easier to test. Favor this style of programming when you can. **Bad:** @@ -699,11 +693,9 @@ const programmerOutput = [ } ]; -const INITIAL_VALUE = 0; - const totalOutput = programmerOutput - .map((programmer) => programmer.linesOfCode) - .reduce((acc, linesOfCode) => acc + linesOfCode, INITIAL_VALUE); + .map(output => output.linesOfCode) + .reduce((totalLines, lines) => totalLines + lines); ``` **[⬆ back to top](#table-of-contents)** @@ -835,7 +827,7 @@ function travelToTexas(vehicle) { **[⬆ back to top](#table-of-contents)** ### Avoid type-checking (part 2) -If you are working with basic primitive values like strings, integers, and arrays, +If you are working with basic primitive values like strings and integers, and you can't use polymorphism but you still feel the need to type-check, you should consider using TypeScript. It is an excellent alternative to normal JavaScript, as it provides you with static typing on top of standard JavaScript @@ -890,10 +882,11 @@ for (let i = 0; i < list.length; i++) { ``` **[⬆ back to top](#table-of-contents)** -### Remove dead code +### ลบโค้ดที่ไม่ได้ใช้งานออก Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it! It will still be safe in your version history if you still need it. +โค้ดที่ไม่ได้ใช้งานก็เหมือนโค้ดที่ซ้ำซ้อน ซึ่งคุณไม่ควรจะเก็บมันไว้ ถ้าโค้ดนั้นไม่เคยถูกเรียกใช้งานเลย ให้ลบมันออกไปซะ ถ้าคุณยังต้องการมันในภายหลังก็สามารถหาได้ใน version history **Bad:** ```javascript @@ -921,11 +914,9 @@ inventoryTracker('apples', req, 'www.inventory-awesome.io'); ``` **[⬆ back to top](#table-of-contents)** -## **Objects and Data Structures** -### Use getters and setters -JavaScript doesn't have interfaces or types so it is very hard to enforce this -pattern, because we don't have keywords like `public` and `private`. As it is, -using getters and setters to access data on objects is far better than simply +## **Objects และ Data Structures** +### ใช้ getters และ setters +Using getters and setters to access data on objects could be better than simply looking for a property on an object. "Why?" you might ask. Well, here's an unorganized list of reasons why: @@ -934,56 +925,51 @@ to look up and change every accessor in your codebase. * Makes adding validation simple when doing a `set`. * Encapsulates the internal representation. * Easy to add logging and error handling when getting and setting. -* Inheriting this class, you can override default functionality. * You can lazy load your object's properties, let's say getting it from a server. **Bad:** ```javascript -class BankAccount { - constructor() { - this.balance = 1000; - } -} +function makeBankAccount() { + // ... -const bankAccount = new BankAccount(); + return { + balance: 0, + // ... + }; +} -// Buy shoes... -bankAccount.balance -= 100; +const account = makeBankAccount(); +account.balance = 100; ``` **Good:** ```javascript -class BankAccount { - constructor(balance = 1000) { - this._balance = balance; - } +function makeBankAccount() { + // this one is private + let balance = 0; - // It doesn't have to be prefixed with `get` or `set` to be a getter/setter - set balance(amount) { - if (this.verifyIfAmountCanBeSetted(amount)) { - this._balance = amount; - } + // a "getter", made public via the returned object below + function getBalance() { + return balance; } - get balance() { - return this._balance; + // a "setter", made public via the returned object below + function setBalance(amount) { + // ... validate before updating the balance + balance = amount; } - verifyIfAmountCanBeSetted(val) { + return { // ... - } + getBalance, + setBalance, + }; } -const bankAccount = new BankAccount(); - -// Buy shoes... -bankAccount.balance -= shoesPrice; - -// Get balance -let balance = bankAccount.balance; - +const account = makeBankAccount(); +account.setBalance(100); ``` **[⬆ back to top](#table-of-contents)** @@ -1010,13 +996,15 @@ console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined **Good:** ```javascript -const Employee = function (name) { - this.getName = function getName() { - return name; +function makeEmployee(name) { + return { + getName() { + return name; + }, }; -}; +} -const employee = new Employee('John Doe'); +const employee = makeEmployee('John Doe'); console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe delete employee.name; console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe @@ -1025,153 +1013,373 @@ console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe ## **Classes** -### Single Responsibility Principle (SRP) -As stated in Clean Code, "There should never be more than one reason for a class -to change". It's tempting to jam-pack a class with a lot of functionality, like -when you can only take one suitcase on your flight. The issue with this is -that your class won't be conceptually cohesive and it will give it many reasons -to change. Minimizing the amount of times you need to change a class is important. -It's important because if too much functionality is in one class and you modify a piece of it, -it can be difficult to understand how that will affect other dependent modules in -your codebase. +### ใช้ ES2015/ES6 classe แทน ES5 plain function +It's very difficult to get readable class inheritance, construction, and method +definitions for classical ES5 classes. If you need inheritance (and be aware +that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over +classes until you find yourself needing larger and more complex objects. **Bad:** ```javascript -class UserSettings { - constructor(user) { - this.user = user; +const Animal = function(age) { + if (!(this instanceof Animal)) { + throw new Error('Instantiate Animal with `new`'); } - changeSettings(settings) { - if (this.verifyCredentials()) { - // ... - } + this.age = age; +}; + +Animal.prototype.move = function move() {}; + +const Mammal = function(age, furColor) { + if (!(this instanceof Mammal)) { + throw new Error('Instantiate Mammal with `new`'); } - verifyCredentials() { - // ... + Animal.call(this, age); + this.furColor = furColor; +}; + +Mammal.prototype = Object.create(Animal.prototype); +Mammal.prototype.constructor = Mammal; +Mammal.prototype.liveBirth = function liveBirth() {}; + +const Human = function(age, furColor, languageSpoken) { + if (!(this instanceof Human)) { + throw new Error('Instantiate Human with `new`'); } -} + + Mammal.call(this, age, furColor); + this.languageSpoken = languageSpoken; +}; + +Human.prototype = Object.create(Mammal.prototype); +Human.prototype.constructor = Human; +Human.prototype.speak = function speak() {}; ``` **Good:** ```javascript -class UserAuth { - constructor(user) { - this.user = user; +class Animal { + constructor(age) { + this.age = age; } - verifyCredentials() { - // ... - } + move() { /* ... */ } } - -class UserSettings { - constructor(user) { - this.user = user; - this.auth = new UserAuth(user); +class Mammal extends Animal { + constructor(age, furColor) { + super(age); + this.furColor = furColor; } - changeSettings(settings) { - if (this.auth.verifyCredentials()) { - // ... - } + liveBirth() { /* ... */ } +} + +class Human extends Mammal { + constructor(age, furColor, languageSpoken) { + super(age, furColor); + this.languageSpoken = languageSpoken; } + + speak() { /* ... */ } } ``` **[⬆ back to top](#table-of-contents)** -### Open/Closed Principle (OCP) -As stated by Bertrand Meyer, "software entities (classes, modules, functions, -etc.) should be open for extension, but closed for modification." What does that -mean though? This principle basically states that you should allow users to -add new functionalities without changing existing code. + +### ใช้ method chaining +This pattern is very useful in JavaScript and you see it in many libraries such +as jQuery and Lodash. It allows your code to be expressive, and less verbose. +For that reason, I say, use method chaining and take a look at how clean your code +will be. In your class functions, simply return `this` at the end of every function, +and you can chain further class methods onto it. **Bad:** ```javascript -class AjaxAdapter extends Adapter { - constructor() { - super(); - this.name = 'ajaxAdapter'; +class Car { + constructor(make, model, color) { + this.make = make; + this.model = model; + this.color = color; } -} -class NodeAdapter extends Adapter { - constructor() { - super(); - this.name = 'nodeAdapter'; + setMake(make) { + this.make = make; } -} -class HttpRequester { - constructor(adapter) { - this.adapter = adapter; + setModel(model) { + this.model = model; } - fetch(url) { - if (this.adapter.name === 'ajaxAdapter') { - return makeAjaxCall(url).then((response) => { - // transform response and return - }); - } else if (this.adapter.name === 'httpNodeAdapter') { - return makeHttpCall(url).then((response) => { - // transform response and return - }); - } + setColor(color) { + this.color = color; } -} -function makeAjaxCall(url) { - // request and return promise + save() { + console.log(this.make, this.model, this.color); + } } -function makeHttpCall(url) { - // request and return promise -} +const car = new Car('Ford','F-150','red'); +car.setColor('pink'); +car.save(); ``` **Good:** ```javascript -class AjaxAdapter extends Adapter { - constructor() { - super(); - this.name = 'ajaxAdapter'; - } - - request(url) { - // request and return promise +class Car { + constructor(make, model, color) { + this.make = make; + this.model = model; + this.color = color; } -} -class NodeAdapter extends Adapter { - constructor() { - super(); - this.name = 'nodeAdapter'; + setMake(make) { + this.make = make; + // NOTE: Returning this for chaining + return this; } - request(url) { - // request and return promise + setModel(model) { + this.model = model; + // NOTE: Returning this for chaining + return this; } -} -class HttpRequester { - constructor(adapter) { - this.adapter = adapter; + setColor(color) { + this.color = color; + // NOTE: Returning this for chaining + return this; } - fetch(url) { - return this.adapter.request(url).then((response) => { - // transform response and return - }); + save() { + console.log(this.make, this.model, this.color); + // NOTE: Returning this for chaining + return this; } } + +const car = new Car('Ford','F-150','red') + .setColor('pink') + .save(); ``` **[⬆ back to top](#table-of-contents)** - -### Liskov Substitution Principle (LSP) -This is a scary term for a very simple concept. It's formally defined as "If S +### ใช้ composition แทน inheritance +As stated famously in [*Design Patterns*](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, +you should prefer composition over inheritance where you can. There are lots of +good reasons to use inheritance and lots of good reasons to use composition. +The main point for this maxim is that if your mind instinctively goes for +inheritance, try to think if composition could model your problem better. In some +cases it can. + +You might be wondering then, "when should I use inheritance?" It +depends on your problem at hand, but this is a decent list of when inheritance +makes more sense than composition: + +1. Your inheritance represents an "is-a" relationship and not a "has-a" +relationship (Human->Animal vs. User->UserDetails). +2. You can reuse code from the base classes (Humans can move like all animals). +3. You want to make global changes to derived classes by changing a base class. +(Change the caloric expenditure of all animals when they move). + +**Bad:** +```javascript +class Employee { + constructor(name, email) { + this.name = name; + this.email = email; + } + + // ... +} + +// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee +class EmployeeTaxData extends Employee { + constructor(ssn, salary) { + super(); + this.ssn = ssn; + this.salary = salary; + } + + // ... +} +``` + +**Good:** +```javascript +class EmployeeTaxData { + constructor(ssn, salary) { + this.ssn = ssn; + this.salary = salary; + } + + // ... +} + +class Employee { + constructor(name, email) { + this.name = name; + this.email = email; + } + + setTaxData(ssn, salary) { + this.taxData = new EmployeeTaxData(ssn, salary); + } + // ... +} +``` +**[⬆ back to top](#table-of-contents)** + +## **SOLID** +### Single Responsibility Principle (SRP) +As stated in Clean Code, "There should never be more than one reason for a class +to change". It's tempting to jam-pack a class with a lot of functionality, like +when you can only take one suitcase on your flight. The issue with this is +that your class won't be conceptually cohesive and it will give it many reasons +to change. Minimizing the amount of times you need to change a class is important. +It's important because if too much functionality is in one class and you modify +a piece of it, it can be difficult to understand how that will affect other +dependent modules in your codebase. + +**Bad:** +```javascript +class UserSettings { + constructor(user) { + this.user = user; + } + + changeSettings(settings) { + if (this.verifyCredentials()) { + // ... + } + } + + verifyCredentials() { + // ... + } +} +``` + +**Good:** +```javascript +class UserAuth { + constructor(user) { + this.user = user; + } + + verifyCredentials() { + // ... + } +} + + +class UserSettings { + constructor(user) { + this.user = user; + this.auth = new UserAuth(user); + } + + changeSettings(settings) { + if (this.auth.verifyCredentials()) { + // ... + } + } +} +``` +**[⬆ back to top](#table-of-contents)** + +### Open/Closed Principle (OCP) +As stated by Bertrand Meyer, "software entities (classes, modules, functions, +etc.) should be open for extension, but closed for modification." What does that +mean though? This principle basically states that you should allow users to +add new functionalities without changing existing code. + +**Bad:** +```javascript +class AjaxAdapter extends Adapter { + constructor() { + super(); + this.name = 'ajaxAdapter'; + } +} + +class NodeAdapter extends Adapter { + constructor() { + super(); + this.name = 'nodeAdapter'; + } +} + +class HttpRequester { + constructor(adapter) { + this.adapter = adapter; + } + + fetch(url) { + if (this.adapter.name === 'ajaxAdapter') { + return makeAjaxCall(url).then((response) => { + // transform response and return + }); + } else if (this.adapter.name === 'httpNodeAdapter') { + return makeHttpCall(url).then((response) => { + // transform response and return + }); + } + } +} + +function makeAjaxCall(url) { + // request and return promise +} + +function makeHttpCall(url) { + // request and return promise +} +``` + +**Good:** +```javascript +class AjaxAdapter extends Adapter { + constructor() { + super(); + this.name = 'ajaxAdapter'; + } + + request(url) { + // request and return promise + } +} + +class NodeAdapter extends Adapter { + constructor() { + super(); + this.name = 'nodeAdapter'; + } + + request(url) { + // request and return promise + } +} + +class HttpRequester { + constructor(adapter) { + this.adapter = adapter; + } + + fetch(url) { + return this.adapter.request(url).then((response) => { + // transform response and return + }); + } +} +``` +**[⬆ back to top](#table-of-contents)** + +### Liskov Substitution Principle (LSP) +This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, @@ -1229,7 +1437,7 @@ function renderLargeRectangles(rectangles) { rectangles.forEach((rectangle) => { rectangle.setWidth(4); rectangle.setHeight(5); - const area = rectangle.getArea(); // BAD: Will return 25 for Square. Should be 20. + const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. rectangle.render(area); }); } @@ -1251,17 +1459,9 @@ class Shape { } class Rectangle extends Shape { - constructor() { + constructor(width, height) { super(); - this.width = 0; - this.height = 0; - } - - setWidth(width) { this.width = width; - } - - setHeight(height) { this.height = height; } @@ -1271,12 +1471,8 @@ class Rectangle extends Shape { } class Square extends Shape { - constructor() { + constructor(length) { super(); - this.length = 0; - } - - setLength(length) { this.length = length; } @@ -1287,21 +1483,12 @@ class Square extends Shape { function renderLargeShapes(shapes) { shapes.forEach((shape) => { - switch (shape.constructor.name) { - case 'Square': - shape.setLength(5); - break; - case 'Rectangle': - shape.setWidth(4); - shape.setHeight(5); - } - const area = shape.getArea(); shape.render(area); }); } -const shapes = [new Rectangle(), new Rectangle(), new Square()]; +const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; renderLargeShapes(shapes); ``` **[⬆ back to top](#table-of-contents)** @@ -1318,7 +1505,8 @@ duck typing. A good example to look at that demonstrates this principle in JavaScript is for classes that require large settings objects. Not requiring clients to setup huge amounts of options is beneficial, because most of the time they won't need -all of the settings. Making them optional helps prevent having a "fat interface". +all of the settings. Making them optional helps prevent having a +"fat interface". **Bad:** ```javascript @@ -1387,7 +1575,7 @@ depend on abstractions. 2. Abstractions should not depend upon details. Details should depend on abstractions. -This can be hard to understand at first, but if you've worked with Angular.js, +This can be hard to understand at first, but if you've worked with AngularJS, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. @@ -1475,230 +1663,6 @@ inventoryTracker.requestItems(); ``` **[⬆ back to top](#table-of-contents)** -### Prefer ES2015/ES6 classes over ES5 plain functions -It's very difficult to get readable class inheritance, construction, and method -definitions for classical ES5 classes. If you need inheritance (and be aware -that you might not), then prefer classes. However, prefer small functions over -classes until you find yourself needing larger and more complex objects. - -**Bad:** -```javascript -const Animal = function(age) { - if (!(this instanceof Animal)) { - throw new Error('Instantiate Animal with `new`'); - } - - this.age = age; -}; - -Animal.prototype.move = function move() {}; - -const Mammal = function(age, furColor) { - if (!(this instanceof Mammal)) { - throw new Error('Instantiate Mammal with `new`'); - } - - Animal.call(this, age); - this.furColor = furColor; -}; - -Mammal.prototype = Object.create(Animal.prototype); -Mammal.prototype.constructor = Mammal; -Mammal.prototype.liveBirth = function liveBirth() {}; - -const Human = function(age, furColor, languageSpoken) { - if (!(this instanceof Human)) { - throw new Error('Instantiate Human with `new`'); - } - - Mammal.call(this, age, furColor); - this.languageSpoken = languageSpoken; -}; - -Human.prototype = Object.create(Mammal.prototype); -Human.prototype.constructor = Human; -Human.prototype.speak = function speak() {}; -``` - -**Good:** -```javascript -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() { /* ... */ } -} -``` -**[⬆ back to top](#table-of-contents)** - - -### Use method chaining -This pattern is very useful in JavaScript and you see it in many libraries such -as jQuery and Lodash. It allows your code to be expressive, and less verbose. -For that reason, I say, use method chaining and take a look at how clean your code -will be. In your class functions, simply return `this` at the end of every function, -and you can chain further class methods onto it. - -**Bad:** -```javascript -class Car { - constructor() { - this.make = 'Honda'; - this.model = 'Accord'; - this.color = 'white'; - } - - 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(); -car.setColor('pink'); -car.setMake('Ford'); -car.setModel('F-150'); -car.save(); -``` - -**Good:** -```javascript -class Car { - constructor() { - this.make = 'Honda'; - this.model = 'Accord'; - this.color = 'white'; - } - - setMake(make) { - this.make = make; - // NOTE: Returning this for chaining - return this; - } - - setModel(model) { - this.model = model; - // NOTE: Returning this for chaining - return this; - } - - setColor(color) { - this.color = color; - // NOTE: Returning this for chaining - return this; - } - - save() { - console.log(this.make, this.model, this.color); - // NOTE: Returning this for chaining - return this; - } -} - -const car = new Car() - .setColor('pink') - .setMake('Ford') - .setModel('F-150') - .save(); -``` -**[⬆ back to top](#table-of-contents)** - -### Prefer composition over inheritance -As stated famously in [*Design Patterns*](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, -you should prefer composition over inheritance where you can. There are lots of -good reasons to use inheritance and lots of good reasons to use composition. -The main point for this maxim is that if your mind instinctively goes for -inheritance, try to think if composition could model your problem better. In some -cases it can. - -You might be wondering then, "when should I use inheritance?" It -depends on your problem at hand, but this is a decent list of when inheritance -makes more sense than composition: - -1. Your inheritance represents an "is-a" relationship and not a "has-a" -relationship (Human->Animal vs. User->UserDetails). -2. You can reuse code from the base classes (Humans can move like all animals). -3. You want to make global changes to derived classes by changing a base class. -(Change the caloric expenditure of all animals when they move). - -**Bad:** -```javascript -class Employee { - constructor(name, email) { - this.name = name; - this.email = email; - } - - // ... -} - -// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee -class EmployeeTaxData extends Employee { - constructor(ssn, salary) { - super(); - this.ssn = ssn; - this.salary = salary; - } - - // ... -} -``` - -**Good:** -```javascript -class EmployeeTaxData { - constructor(ssn, salary) { - this.ssn = ssn; - this.salary = salary; - } - - // ... -} - -class Employee { - constructor(name, email) { - this.name = name; - this.email = email; - } - - setTaxData(ssn, salary) { - this.taxData = new EmployeeTaxData(ssn, salary); - } - // ... -} -``` -**[⬆ back to top](#table-of-contents)** - ## **Testing** Testing is more important than shipping. If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you @@ -1708,19 +1672,18 @@ you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a [good coverage tool](http://gotwarlost.github.io/istanbul/). -There's no excuse to not write tests. There's [plenty of good JS test frameworks] -(http://jstherightway.org/#testing-tools), so find one that your team prefers. +There's no excuse to not write tests. There are [plenty of good JS test frameworks](http://jstherightway.org/#testing-tools), so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one. -### Single concept per test +### หนึ่งเทสต่อหนึ่งคอนเซปต์ **Bad:** ```javascript -const assert = require('assert'); +import assert from 'assert'; describe('MakeMomentJSGreatAgain', () => { it('handles date boundaries', () => { @@ -1728,7 +1691,7 @@ describe('MakeMomentJSGreatAgain', () => { date = new MakeMomentJSGreatAgain('1/1/2015'); date.addDays(30); - date.shouldEqual('1/31/2015'); + assert.equal('1/31/2015', date); date = new MakeMomentJSGreatAgain('2/1/2016'); date.addDays(28); @@ -1743,13 +1706,13 @@ describe('MakeMomentJSGreatAgain', () => { **Good:** ```javascript -const assert = require('assert'); +import assert from 'assert'; describe('MakeMomentJSGreatAgain', () => { it('handles 30-day months', () => { const date = new MakeMomentJSGreatAgain('1/1/2015'); date.addDays(30); - date.shouldEqual('1/31/2015'); + assert.equal('1/31/2015', date); }); it('handles leap year', () => { @@ -1768,17 +1731,20 @@ describe('MakeMomentJSGreatAgain', () => { **[⬆ back to top](#table-of-contents)** ## **Concurrency** -### Use Promises, not callbacks +### ใช้ Promises แทน callbacks Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6, Promises are a built-in global type. Use them! **Bad:** ```javascript -require('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (requestErr, response) => { +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 { - require('fs').writeFile('article.html', response.body, (writeErr) => { + writeFile('article.html', response.body, (writeErr) => { if (writeErr) { console.error(writeErr); } else { @@ -1792,9 +1758,12 @@ require('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (req **Good:** ```javascript -require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') +import { get } from 'request'; +import { writeFile } from 'fs'; + +get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') .then((response) => { - return require('fs-promise').writeFile('article.html', response); + return writeFile('article.html', response); }) .then(() => { console.log('File written'); @@ -1806,7 +1775,7 @@ require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Marti%20%60%60%60%20**[%E2%AC%86%20back%20to%20top](#table-of-contents)**%20-###%20Async/Await%20are%20even%20cleaner%20than%20Promises+###%20%E0%B9%83%E0%B8%8A%E0%B9%89%20Async/Await%20%E0%B9%81%E0%B8%97%E0%B8%99%20Promises%20Promises%20are%20a%20very%20clean%20alternative%20to%20callbacks,%20but%20ES2017/ES8%20brings%20async%20and%20await%20which%20offer%20an%20even%20cleaner%20solution.%20All%20you%20need%20is%20a%20function%20that%20is%20prefixed%20in%20an%20%60async%60%20keyword,%20and%20then%20you%20can%20write%20your%20logic%20imperatively%20without@@%20-1815,9%20+1784,12%20@@%20today!%20%20**Bad:**%20%60%60%60javascript-require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') +import { get } from 'request-promise'; +import { writeFile } from 'fs-promise'; + +get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') .then((response) => { - return require('fs-promise').writeFile('article.html', response); + return writeFile('article.html', response); }) .then(() => { console.log('File written'); @@ -1830,10 +1802,13 @@ require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Marti%20%20**Good:**%20%60%60%60javascript+import%20%7B%20get%20%7D%20from'request-promise'; +import { writeFile } from 'fs-promise'; + async function getCleanCodeArticle() { try { - const response = await require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin'); - await require('fs-promise').writeFile('article.html', response); + 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); @@ -1849,7 +1824,7 @@ identified when something in your program has gone wrong and it's letting you know by stopping function execution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace. -### Don't ignore caught errors +### อย่าเพิกเฉยต่อ error Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (`console.log`) isn't much better as often times it can get lost in a sea of things printed @@ -1881,36 +1856,36 @@ try { } ``` -### Don't ignore rejected promises +### อย่าละเลย rejected promises For the same reason you shouldn't ignore caught errors from `try/catch`. **Bad:** ```javascript getdata() -.then((data) => { - functionThatMightThrow(data); -}) -.catch((error) => { - console.log(error); -}); + .then((data) => { + functionThatMightThrow(data); + }) + .catch((error) => { + console.log(error); + }); ``` **Good:** ```javascript getdata() -.then((data) => { - functionThatMightThrow(data); -}) -.catch((error) => { - // One option (more noisy than console.log): - console.error(error); - // Another option: - notifyUserOfError(error); - // Another option: - reportErrorToService(error); - // OR do all three! -}); + .then((data) => { + functionThatMightThrow(data); + }) + .catch((error) => { + // One option (more noisy than console.log): + console.error(error); + // Another option: + notifyUserOfError(error); + // Another option: + reportErrorToService(error); + // OR do all three! + }); ``` **[⬆ back to top](#table-of-contents)** @@ -1951,8 +1926,8 @@ class Alpaca {} const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30; -const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; -const artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; +const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; +const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles']; function eraseDatabase() {} function restoreDatabase() {} @@ -1963,7 +1938,7 @@ class Alpaca {} **[⬆ back to top](#table-of-contents)** -### Function callers and callees should be close +### ตัวเรียก function และ function ที่ถูกเรียกควรอยู่ใกล้กัน If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee. We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way. @@ -2003,7 +1978,7 @@ class PerformanceReview { } } -const review = new PerformanceReview(user); +const review = new PerformanceReview(employee); review.perfReview(); ``` @@ -2049,7 +2024,7 @@ review.perfReview(); **[⬆ back to top](#table-of-contents)** ## **Comments** -### Only comment things that have business logic complexity. +### คอมเมนต์แต่สิ่งที่เป็น business logic ที่ซับซ้อน Comments are an apology, not a requirement. Good code *mostly* documents itself. **Bad:** @@ -2092,8 +2067,9 @@ function hashIt(data) { ``` **[⬆ back to top](#table-of-contents)** -### Don't leave commented out code in your codebase +### ไม่ควรเหลือโค้ดที่ถูกคอมเมนต์เอาไว้ Version control exists for a reason. Leave old code in your history. +เนื่องจากเรามี Version Control ควรจะเก็บโค้ดเก่าไว้ที่นั่น **Bad:** ```javascript @@ -2174,10 +2150,19 @@ const actions = function() { This is also available in other languages: - ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [fesnt/clean-code-javascript](https://github.com/fesnt/clean-code-javascript) - - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese**: [alivebao/clean-code-js](https://github.com/alivebao/clean-code-js) + - ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Uruguay.png) **Spanish**: [andersontr15/clean-code-javascript](https://github.com/andersontr15/clean-code-javascript-es) + - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese**: + - [alivebao/clean-code-js](https://github.com/alivebao/clean-code-js) + - [beginor/clean-code-javascript](https://github.com/beginor/clean-code-javascript) - ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [marcbruederlin/clean-code-javascript](https://github.com/marcbruederlin/clean-code-javascript) - ![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [qkraudghgh/clean-code-javascript-ko](https://github.com/qkraudghgh/clean-code-javascript-ko) - - ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [BoryaMogila/clean-code-javascript-ru/](https://github.com/BoryaMogila/clean-code-javascript-ru/) - + - ![pl](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Poland.png) **Polish**: [greg-dev/clean-code-javascript-pl](https://github.com/greg-dev/clean-code-javascript-pl) + - ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: + - [BoryaMogila/clean-code-javascript-ru/](https://github.com/BoryaMogila/clean-code-javascript-ru/) + - [maksugr/clean-code-javascript](https://github.com/maksugr/clean-code-javascript) + - ![vi](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnamese**: [hienvd/clean-code-javascript/](https://github.com/hienvd/clean-code-javascript/) + - ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [mitsuruog/clean-code-javascript/](https://github.com/mitsuruog/clean-code-javascript/) + - ![id](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Indonesia.png) **Indonesia**: + [andirkh/clean-code-javascript/](https://github.com/andirkh/clean-code-javascript/) **[⬆ back to top](#table-of-contents)**