diff --git a/README.md b/README.md index 056dbac6..f1159781 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,34 @@ - # 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) + +1. [Introduction](#introduction) +2. [Variables](#variables) +3. [Functions](#functions) +4. [Objects and Data Structures](#objects-and-data-structures) +5. [Classes](#classes) +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) +you shout when reading code](https://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), +[_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. +[readable, reusable, and refactorable](https://github.com/ryanmcdermott/3rs-of-software-architecture) software in JavaScript. 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 @@ -42,22 +44,27 @@ we review it with our peers. Don't beat yourself up for first drafts that need improvement. Beat up the code instead! ## **Variables** + ### Use meaningful and pronounceable variable names **Bad:** + ```javascript -const yyyymmdstr = moment().format('YYYY/MM/DD'); +const yyyymmdstr = moment().format("YYYY/MM/DD"); ``` **Good:** + ```javascript -const currentDate = moment().format('YYYY/MM/DD'); +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(); @@ -65,14 +72,17 @@ 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 +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 @@ -80,46 +90,56 @@ Make your names searchable. Tools like can help identify unnamed constants. **Bad:** + ```javascript // What the heck is 86400000 for? setTimeout(blastOff, 86400000); - ``` **Good:** -```javascript -// Declare them as capitalized `const` globals. -const MILLISECONDS_IN_A_DAY = 86400000; -setTimeout(blastOff, MILLISECONDS_IN_A_DAY); +```javascript +// Declare them as capitalized named constants. +const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000; +setTimeout(blastOff, MILLISECONDS_PER_DAY); ``` + **[⬆ back to top](#table-of-contents)** ### Use explanatory variables + **Bad:** + ```javascript -const address = 'One Infinite Loop, Cupertino 95014'; +const address = "One Infinite Loop, Cupertino 95014"; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; -saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]); +saveCityZipCode( + address.match(cityZipCodeRegex)[1], + address.match(cityZipCodeRegex)[2] +); ``` **Good:** + ```javascript -const address = 'One Infinite Loop, Cupertino 95014'; +const address = "One Infinite Loop, Cupertino 95014"; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; -const [, city, zipCode] = address.match(cityZipCodeRegex) || []; +const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; 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) => { +const locations = ["Austin", "New York", "San Francisco"]; +locations.forEach(l => { doStuff(); doSomeOtherStuff(); // ... @@ -131,9 +151,10 @@ locations.forEach((l) => { ``` **Good:** + ```javascript -const locations = ['Austin', 'New York', 'San Francisco']; -locations.forEach((location) => { +const locations = ["Austin", "New York", "San Francisco"]; +locations.forEach(location => { doStuff(); doSomeOtherStuff(); // ... @@ -142,61 +163,74 @@ locations.forEach((location) => { dispatch(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. **Bad:** + ```javascript const Car = { - carMake: 'Honda', - carModel: 'Accord', - carColor: 'Blue' + carMake: "Honda", + carModel: "Accord", + carColor: "Blue" }; -function paintCar(car) { - car.carColor = 'Red'; +function paintCar(car, color) { + car.carColor = color; } ``` **Good:** + ```javascript const Car = { - make: 'Honda', - model: 'Accord', - color: 'Blue' + make: "Honda", + model: "Accord", + color: "Blue" }; -function paintCar(car) { - car.color = 'Red'; +function paintCar(car, color) { + car.color = color; } ``` + **[⬆ back to top](#table-of-contents)** -### Use default arguments instead of short circuiting or conditionals +### Use default parameters instead of short circuiting or conditionals + +Default parameters are often cleaner than short circuiting. Be aware that if you +use them, your function will only provide default values for `undefined` +arguments. Other "falsy" values such as `''`, `""`, `false`, `null`, `0`, and +`NaN`, will not be replaced by a default value. **Bad:** + ```javascript function createMicrobrewery(name) { - const breweryName = name || 'Hipster Brew Co.'; + const breweryName = name || "Hipster Brew Co."; // ... } - ``` **Good:** + ```javascript -function createMicrobrewery(breweryName = 'Hipster Brew Co.') { +function createMicrobrewery(name = "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 @@ -212,52 +246,60 @@ 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 +To make it obvious what properties the function expects, you can use the ES2015/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. + properties are being used. +2. It can be used to simulate named parameters. +3. 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. +4. Linters can warn you about unused properties, which would be impossible + without destructuring. **Bad:** + ```javascript function createMenu(title, body, buttonText, cancellable) { // ... } + +createMenu("Foo", "Bar", "Baz", true); + ``` **Good:** + ```javascript function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ - title: 'Foo', - body: 'Bar', - buttonText: 'Baz', + title: "Foo", + body: "Bar", + buttonText: "Baz", cancellable: true }); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 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 +When you can isolate a function to just one action, it 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. **Bad:** + ```javascript function emailClients(clients) { - clients.forEach((client) => { + clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); @@ -267,23 +309,24 @@ function emailClients(clients) { ``` **Good:** + ```javascript -function emailClients(clients) { - clients - .filter(isClientActive) - .forEach(email); +function emailActiveClients(clients) { + clients.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 **Bad:** + ```javascript function addToDate(date, month) { // ... @@ -291,11 +334,12 @@ function addToDate(date, month) { const date = new Date(); -// It's hard to to tell from the function name what is added +// It's hard to tell from the function name what is added addToDate(date, 1); ``` **Good:** + ```javascript function addMonthToDate(month, date) { // ... @@ -304,77 +348,83 @@ function addMonthToDate(month, date) { const date = new Date(); addMonthToDate(1, date); ``` + **[⬆ back to top](#table-of-contents)** ### Functions should only be one level of abstraction + 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 = [ // ... ]; - const statements = code.split(' '); + const statements = code.split(" "); const tokens = []; - REGEXES.forEach((REGEX) => { - statements.forEach((statement) => { + REGEXES.forEach(REGEX => { + statements.forEach(statement => { // ... }); }); const ast = []; - tokens.forEach((token) => { + tokens.forEach(token => { // lex... }); - ast.forEach((node) => { + ast.forEach(node => { // parse... }); } ``` **Good:** + ```javascript +function parseBetterJSAlternative(code) { + const tokens = tokenize(code); + const syntaxTree = parse(tokens); + syntaxTree.forEach(node => { + // parse... + }); +} + function tokenize(code) { const REGEXES = [ // ... ]; - const statements = code.split(' '); + const statements = code.split(" "); const tokens = []; - REGEXES.forEach((REGEX) => { - statements.forEach((statement) => { - tokens.push( /* ... */ ); + REGEXES.forEach(REGEX => { + statements.forEach(statement => { + tokens.push(/* ... */); }); }); return tokens; } -function lexer(tokens) { - const ast = []; - tokens.forEach((token) => { - ast.push( /* ... */ ); +function parse(tokens) { + const syntaxTree = []; + tokens.forEach(token => { + syntaxTree.push(/* ... */); }); - return ast; -} - -function parseBetterJSAlternative(code) { - const tokens = tokenize(code); - const ast = lexer(tokens); - ast.forEach((node) => { - // parse... - }); + return syntaxTree; } ``` + **[⬆ 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. @@ -391,15 +441,16 @@ duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class. Getting the abstraction right is critical, that's why you should follow the -SOLID principles laid out in the *Classes* section. Bad abstractions can be +SOLID principles laid out in the _Classes_ section. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself updating multiple places anytime you want to change one thing. **Bad:** + ```javascript function showDeveloperList(developers) { - developers.forEach((developer) => { + developers.forEach(developer => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); @@ -414,7 +465,7 @@ function showDeveloperList(developers) { } function showManagerList(managers) { - managers.forEach((manager) => { + managers.forEach(manager => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); @@ -430,81 +481,93 @@ function showManagerList(managers) { ``` **Good:** + ```javascript -function showList(employees) { - employees.forEach((employee) => { +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); }); } ``` + **[⬆ back to top](#table-of-contents)** ### Set default objects with Object.assign **Bad:** + ```javascript const menuConfig = { title: null, - body: 'Bar', + 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; + 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:** + ```javascript const menuConfig = { - title: 'Order', + title: "Order", // User did not include 'body' key - buttonText: 'Send', + buttonText: "Send", cancellable: true }; function createMenu(config) { - config = Object.assign({ - title: 'Foo', - body: 'Bar', - buttonText: 'Baz', - cancellable: true - }, config); - + let finalConfig = Object.assign( + { + title: "Foo", + body: "Bar", + buttonText: "Baz", + cancellable: true + }, + config + ); + return finalConfig // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ... } createMenu(menuConfig); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ back to top](#table-of-contents)** ### Don't use flags as function parameters + Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean. **Bad:** + ```javascript function createFile(name, temp) { if (temp) { @@ -516,6 +579,7 @@ function createFile(name, temp) { ``` **Good:** + ```javascript function createFile(name) { fs.create(name); @@ -525,9 +589,11 @@ function createTempFile(name) { createFile(`./temp/${name}`); } ``` + **[⬆ back to top](#table-of-contents)** ### Avoid Side Effects (part 1) + A function produces a side effect if it does anything other than take a value in and return another value or values. A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a @@ -544,13 +610,14 @@ and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers. **Bad:** + ```javascript // Global variable referenced by following function. // If we had another function that used this name, now it'd be an array and it could break it. -let name = 'Ryan McDermott'; +let name = "Ryan McDermott"; function splitIntoFirstAndLastName() { - name = name.split(' '); + name = name.split(" "); } splitIntoFirstAndLastName(); @@ -559,53 +626,61 @@ console.log(name); // ['Ryan', 'McDermott']; ``` **Good:** + ```javascript function splitIntoFirstAndLastName(name) { - return name.split(' '); + return name.split(" "); } -const name = 'Ryan McDermott'; +const name = "Ryan McDermott"; const newName = splitIntoFirstAndLastName(name); console.log(name); // 'Ryan McDermott'; console.log(newName); // ['Ryan', 'McDermott']; ``` + **[⬆ back to top](#table-of-contents)** ### 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 -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 -situation: - -The user clicks the "Purchase", button which calls a `purchase` function that + +In JavaScript, some values are unchangeable (immutable) and some are changeable +(mutable). Objects and arrays are two kinds of mutable values so it's important +to handle them carefully when they're passed as parameters to a function. A +JavaScript function can change an object's properties or alter the contents of +an array which could easily cause bugs elsewhere. + +Suppose there's a function that accepts an array parameter representing a +shopping cart. If the function makes a change in that shopping cart array - +by adding an item to purchase, for example - then any other function that +uses that same `cart` array will be affected by this addition. That may be +great, however it could also be bad. Let's imagine a bad situation: + +The user clicks the "Purchase" button which calls a `purchase` function that spawns a network request and sends the `cart` array to the server. Because of a bad network connection, the `purchase` function has to keep retrying the -request. Now, what if in the meantime the user accidentally clicks "Add to Cart" +request. Now, what if in the meantime the user accidentally clicks an "Add to Cart" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function -will send the accidentally added item because it has a reference to a shopping -cart array that the `addItemToCart` function modified by adding an unwanted -item. +will send the accidentally added item because the `cart` array was modified. -A great solution would be for the `addItemToCart` to always clone the `cart`, -edit it, and return the clone. This ensures that no other functions that are -holding onto a reference of the shopping cart will be affected by any changes. +A great solution would be for the `addItemToCart` function to always clone the +`cart`, edit it, and return the clone. This would ensure that functions that are still +using the old shopping cart wouldn't be affected by the 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 -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, -this isn't a big issue in practice because there are -[great libraries](https://facebook.github.io/immutable-js/) that allow -this kind of programming approach to be fast and not as memory intensive as -it would be for you to manually clone objects and arrays. +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 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, + this isn't a big issue in practice because there are + [great libraries](https://facebook.github.io/immutable-js/) that allow + this kind of programming approach to be fast and not as memory intensive as + it would be for you to manually clone objects and arrays. **Bad:** + ```javascript const addItemToCart = (cart, item) => { cart.push({ item, date: Date.now() }); @@ -613,15 +688,17 @@ const addItemToCart = (cart, item) => { ``` **Good:** + ```javascript const addItemToCart = (cart, item) => { - return [...cart, { item, date : Date.now() }]; + return [...cart, { item, date: Date.now() }]; }; ``` **[⬆ back to top](#table-of-contents)** ### Don't write to global functions + Polluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to @@ -633,6 +710,7 @@ the difference between the first and last elements of an array? This is why it would be much better to just use ES2015/ES6 classes and simply extend the `Array` global. **Bad:** + ```javascript Array.prototype.diff = function diff(comparisonArray) { const hash = new Set(comparisonArray); @@ -641,6 +719,7 @@ Array.prototype.diff = function diff(comparisonArray) { ``` **Good:** + ```javascript class SuperArray extends Array { diff(comparisonArray) { @@ -649,27 +728,33 @@ class SuperArray extends Array { } } ``` + **[⬆ back to top](#table-of-contents)** ### 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:** + ```javascript const programmerOutput = [ { - name: 'Uncle Bobby', + name: "Uncle Bobby", linesOfCode: 500 - }, { - name: 'Suzie Q', + }, + { + name: "Suzie Q", linesOfCode: 1500 - }, { - name: 'Jimmy Gosling', + }, + { + name: "Jimmy Gosling", linesOfCode: 150 - }, { - name: 'Gracie Hopper', + }, + { + name: "Gracie Hopper", linesOfCode: 1000 } ]; @@ -682,55 +767,63 @@ for (let i = 0; i < programmerOutput.length; i++) { ``` **Good:** + ```javascript const programmerOutput = [ { - name: 'Uncle Bobby', + name: "Uncle Bobby", linesOfCode: 500 - }, { - name: 'Suzie Q', + }, + { + name: "Suzie Q", linesOfCode: 1500 - }, { - name: 'Jimmy Gosling', + }, + { + name: "Jimmy Gosling", linesOfCode: 150 - }, { - name: 'Gracie Hopper', + }, + { + name: "Gracie Hopper", linesOfCode: 1000 } ]; -const INITIAL_VALUE = 0; - -const totalOutput = programmerOutput - .map((programmer) => programmer.linesOfCode) - .reduce((acc, linesOfCode) => acc + linesOfCode, INITIAL_VALUE); +const totalOutput = programmerOutput.reduce( + (totalLines, output) => totalLines + output.linesOfCode, + 0 +); ``` + **[⬆ back to top](#table-of-contents)** ### Encapsulate conditionals **Bad:** + ```javascript -if (fsm.state === 'fetching' && isEmpty(listNode)) { +if (fsm.state === "fetching" && isEmpty(listNode)) { // ... } ``` **Good:** + ```javascript function shouldShowSpinner(fsm, listNode) { - return fsm.state === 'fetching' && isEmpty(listNode); + return fsm.state === "fetching" && isEmpty(listNode); } if (shouldShowSpinner(fsmInstance, listNodeInstance)) { // ... } ``` + **[⬆ back to top](#table-of-contents)** ### Avoid negative conditionals **Bad:** + ```javascript function isDOMNodeNotPresent(node) { // ... @@ -742,6 +835,7 @@ if (!isDOMNodeNotPresent(node)) { ``` **Good:** + ```javascript function isDOMNodePresent(node) { // ... @@ -751,9 +845,11 @@ if (isDOMNodePresent(node)) { // ... } ``` + **[⬆ back to top](#table-of-contents)** ### Avoid conditionals + This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without an `if` statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second @@ -764,16 +860,17 @@ are telling your user that your function does more than one thing. Remember, just do one thing. **Bad:** + ```javascript class Airplane { // ... getCruisingAltitude() { switch (this.type) { - case '777': + case "777": return this.getMaxAltitude() - this.getPassengerCount(); - case 'Air Force One': + case "Air Force One": return this.getMaxAltitude(); - case 'Cessna': + case "Cessna": return this.getMaxAltitude() - this.getFuelExpenditure(); } } @@ -781,6 +878,7 @@ class Airplane { ``` **Good:** + ```javascript class Airplane { // ... @@ -807,35 +905,41 @@ class Cessna extends Airplane { } } ``` + **[⬆ back to top](#table-of-contents)** ### Avoid type-checking (part 1) + JavaScript is untyped, which means your functions can take any type of argument. Sometimes you are bitten by this freedom and it becomes tempting to do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs. **Bad:** + ```javascript function travelToTexas(vehicle) { if (vehicle instanceof Bicycle) { - vehicle.pedal(this.currentLocation, new Location('texas')); + vehicle.pedal(this.currentLocation, new Location("texas")); } else if (vehicle instanceof Car) { - vehicle.drive(this.currentLocation, new Location('texas')); + vehicle.drive(this.currentLocation, new Location("texas")); } } ``` **Good:** + ```javascript function travelToTexas(vehicle) { - vehicle.move(this.currentLocation, new Location('texas')); + vehicle.move(this.currentLocation, new Location("texas")); } ``` + **[⬆ 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 @@ -846,26 +950,32 @@ good tests, and have good code reviews. Otherwise, do all of that but with TypeScript (which, like I said, is a great alternative!). **Bad:** + ```javascript function combine(val1, val2) { - if (typeof val1 === 'number' && typeof val2 === 'number' || - typeof val1 === 'string' && typeof val2 === 'string') { + if ( + (typeof val1 === "number" && typeof val2 === "number") || + (typeof val1 === "string" && typeof val2 === "string") + ) { return val1 + val2; } - throw new Error('Must be of type String or Number'); + throw new Error("Must be of type String or Number"); } ``` **Good:** + ```javascript function combine(val1, val2) { return val1 + val2; } ``` + **[⬆ back to top](#table-of-contents)** ### Don't over-optimize + Modern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. [There are good resources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) @@ -873,8 +983,8 @@ for seeing where optimization is lacking. Target those in the meantime, until they are fixed if they can be. **Bad:** -```javascript +```javascript // On old browsers, each iteration with uncached `list.length` would be costly // because of `list.length` recomputation. In modern browsers, this is optimized. for (let i = 0, len = list.length; i < len; i++) { @@ -883,19 +993,23 @@ for (let i = 0, len = list.length; i < len; i++) { ``` **Good:** + ```javascript 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. **Bad:** + ```javascript function oldRequestModule(url) { // ... @@ -906,94 +1020,92 @@ function newRequestModule(url) { } const req = newRequestModule; -inventoryTracker('apples', req, 'www.inventory-awesome.io'); - +inventoryTracker("apples", req, "www.inventory-awesome.io"); ``` **Good:** + ```javascript function newRequestModule(url) { // ... } const req = newRequestModule; -inventoryTracker('apples', req, 'www.inventory-awesome.io'); +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 + +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: -* When you want to do more beyond getting an object property, you don't have -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. - +- When you want to do more beyond getting an object property, you don't have + 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. +- 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)** +**[⬆ back to top](#table-of-contents)** ### Make objects have private members + This can be accomplished through closures (for ES5 and below). **Bad:** -```javascript +```javascript const Employee = function(name) { this.name = name; }; @@ -1002,105 +1114,351 @@ Employee.prototype.getName = function getName() { return this.name; }; -const employee = new Employee('John Doe'); +const employee = new Employee("John Doe"); console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe delete employee.name; 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 ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ back to top](#table-of-contents)** ## **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. + +### 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 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 Mammal extends Animal { + constructor(age, furColor) { + super(age); + this.furColor = furColor; + } -class UserSettings { - constructor(user) { - this.user = user; - this.auth = new UserAuth(user); + liveBirth() { + /* ... */ } +} - changeSettings(settings) { - if (this.auth.verifyCredentials()) { - // ... - } +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 +### 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(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:** + +```javascript +class Car { + constructor(make, model, color) { + this.make = make; + this.model = model; + this.color = color; + } + + 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("Ford", "F-150", "red").setColor("pink").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)** + +## **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'; + this.name = "ajaxAdapter"; } } class NodeAdapter extends Adapter { constructor() { super(); - this.name = 'nodeAdapter'; + this.name = "nodeAdapter"; } } @@ -1110,12 +1468,12 @@ class HttpRequester { } fetch(url) { - if (this.adapter.name === 'ajaxAdapter') { - return makeAjaxCall(url).then((response) => { + 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) => { + } else if (this.adapter.name === "nodeAdapter") { + return makeHttpCall(url).then(response => { // transform response and return }); } @@ -1132,11 +1490,12 @@ function makeHttpCall(url) { ``` **Good:** + ```javascript class AjaxAdapter extends Adapter { constructor() { super(); - this.name = 'ajaxAdapter'; + this.name = "ajaxAdapter"; } request(url) { @@ -1147,7 +1506,7 @@ class AjaxAdapter extends Adapter { class NodeAdapter extends Adapter { constructor() { super(); - this.name = 'nodeAdapter'; + this.name = "nodeAdapter"; } request(url) { @@ -1161,16 +1520,17 @@ class HttpRequester { } fetch(url) { - return this.adapter.request(url).then((response) => { + return this.adapter.request(url).then(response => { // transform response and return }); } } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 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 @@ -1185,6 +1545,7 @@ if you model it using the "is-a" relationship via inheritance, you quickly get into trouble. **Bad:** + ```javascript class Rectangle { constructor() { @@ -1226,10 +1587,10 @@ class Square extends Rectangle { } function renderLargeRectangles(rectangles) { - rectangles.forEach((rectangle) => { + 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); }); } @@ -1239,6 +1600,7 @@ renderLargeRectangles(rectangles); ``` **Good:** + ```javascript class Shape { setColor(color) { @@ -1251,17 +1613,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 +1625,8 @@ class Rectangle extends Shape { } class Square extends Shape { - constructor() { + constructor(length) { super(); - this.length = 0; - } - - setLength(length) { this.length = length; } @@ -1286,430 +1636,210 @@ 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); - } - + shapes.forEach(shape => { 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)** ### Interface Segregation Principle (ISP) + JavaScript doesn't have interfaces so this principle doesn't apply as strictly as others. However, it's important and relevant even with JavaScript's lack of type system. ISP states that "Clients should not be forced to depend upon interfaces that they do not use." Interfaces are implicit contracts in JavaScript because of -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". - -**Bad:** -```javascript -class DOMTraverser { - constructor(settings) { - this.settings = settings; - this.setup(); - } - - setup() { - this.rootNode = this.settings.rootNode; - this.animationModule.setup(); - } - - traverse() { - // ... - } -} - -const $ = new DOMTraverser({ - rootNode: document.getElementsByTagName('body'), - animationModule() {} // Most of the time, we won't need to animate when traversing. - // ... -}); - -``` - -**Good:** -```javascript -class DOMTraverser { - constructor(settings) { - this.settings = settings; - this.options = settings.options; - this.setup(); - } - - setup() { - this.rootNode = this.settings.rootNode; - this.setupOptions(); - } - - setupOptions() { - if (this.options.animationModule) { - // ... - } - } - - traverse() { - // ... - } -} - -const $ = new DOMTraverser({ - rootNode: document.getElementsByTagName('body'), - options: { - animationModule() {} - } -}); -``` -**[⬆ back to top](#table-of-contents)** - -### Dependency Inversion Principle (DIP) -This principle states two essential things: -1. High-level modules should not depend on low-level modules. Both should -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, -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. -It can accomplish this through DI. A huge benefit of this is that it reduces -the coupling between modules. Coupling is a very bad development pattern because -it makes your code hard to refactor. - -As stated previously, JavaScript doesn't have interfaces so the abstractions -that are depended upon are implicit contracts. That is to say, the methods -and properties that an object/class exposes to another object/class. In the -example below, the implicit contract is that any Request module for an -`InventoryTracker` will have a `requestItems` method. - -**Bad:** -```javascript -class InventoryRequester { - constructor() { - this.REQ_METHODS = ['HTTP']; - } - - requestItem(item) { - // ... - } -} - -class InventoryTracker { - constructor(items) { - this.items = items; - - // BAD: We have created a dependency on a specific request implementation. - // We should just have requestItems depend on a request method: `request` - this.requester = new InventoryRequester(); - } - - requestItems() { - this.items.forEach((item) => { - this.requester.requestItem(item); - }); - } -} - -const inventoryTracker = new InventoryTracker(['apples', 'bananas']); -inventoryTracker.requestItems(); -``` - -**Good:** -```javascript -class InventoryTracker { - constructor(items, requester) { - this.items = items; - this.requester = requester; - } - - requestItems() { - this.items.forEach((item) => { - this.requester.requestItem(item); - }); - } -} - -class InventoryRequesterV1 { - constructor() { - this.REQ_METHODS = ['HTTP']; - } - - requestItem(item) { - // ... - } -} - -class InventoryRequesterV2 { - constructor() { - this.REQ_METHODS = ['WS']; - } - - requestItem(item) { - // ... - } -} - -// By constructing our dependencies externally and injecting them, we can easily -// substitute our request module for a fancy new one that uses WebSockets. -const inventoryTracker = new InventoryTracker(['apples', 'bananas'], new InventoryRequesterV2()); -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)** - +duck typing. -### 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. +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". **Bad:** -```javascript -class Car { - constructor() { - this.make = 'Honda'; - this.model = 'Accord'; - this.color = 'white'; - } - - setMake(make) { - this.make = make; - } - setModel(model) { - this.model = model; +```javascript +class DOMTraverser { + constructor(settings) { + this.settings = settings; + this.setup(); } - setColor(color) { - this.color = color; + setup() { + this.rootNode = this.settings.rootNode; + this.settings.animationModule.setup(); } - save() { - console.log(this.make, this.model, this.color); + traverse() { + // ... } } -const car = new Car(); -car.setColor('pink'); -car.setMake('Ford'); -car.setModel('F-150'); -car.save(); +const $ = new DOMTraverser({ + rootNode: document.getElementsByTagName("body"), + animationModule() {} // Most of the time, we won't need to animate when traversing. + // ... +}); ``` **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; +```javascript +class DOMTraverser { + constructor(settings) { + this.settings = settings; + this.options = settings.options; + this.setup(); } - setModel(model) { - this.model = model; - // NOTE: Returning this for chaining - return this; + setup() { + this.rootNode = this.settings.rootNode; + this.setupOptions(); } - setColor(color) { - this.color = color; - // NOTE: Returning this for chaining - return this; + setupOptions() { + if (this.options.animationModule) { + // ... + } } - save() { - console.log(this.make, this.model, this.color); - // NOTE: Returning this for chaining - return this; + traverse() { + // ... } } -const car = new Car() - .setColor('pink') - .setMake('Ford') - .setModel('F-150') - .save(); +const $ = new DOMTraverser({ + rootNode: document.getElementsByTagName("body"), + options: { + animationModule() {} + } +}); ``` + **[⬆ 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. +### Dependency Inversion Principle (DIP) -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: +This principle states two essential things: -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). +1. High-level modules should not depend on low-level modules. Both should + 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 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. +It can accomplish this through DI. A huge benefit of this is that it reduces +the coupling between modules. Coupling is a very bad development pattern because +it makes your code hard to refactor. + +As stated previously, JavaScript doesn't have interfaces so the abstractions +that are depended upon are implicit contracts. That is to say, the methods +and properties that an object/class exposes to another object/class. In the +example below, the implicit contract is that any Request module for an +`InventoryTracker` will have a `requestItems` method. **Bad:** + ```javascript -class Employee { - constructor(name, email) { - this.name = name; - this.email = email; +class InventoryRequester { + constructor() { + this.REQ_METHODS = ["HTTP"]; } - // ... + requestItem(item) { + // ... + } } -// 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; +class InventoryTracker { + constructor(items) { + this.items = items; + + // BAD: We have created a dependency on a specific request implementation. + // We should just have requestItems depend on a request method: `request` + this.requester = new InventoryRequester(); } - // ... + requestItems() { + this.items.forEach(item => { + this.requester.requestItem(item); + }); + } } + +const inventoryTracker = new InventoryTracker(["apples", "bananas"]); +inventoryTracker.requestItems(); ``` **Good:** + ```javascript -class EmployeeTaxData { - constructor(ssn, salary) { - this.ssn = ssn; - this.salary = salary; +class InventoryTracker { + constructor(items, requester) { + this.items = items; + this.requester = requester; } - // ... + requestItems() { + this.items.forEach(item => { + this.requester.requestItem(item); + }); + } } -class Employee { - constructor(name, email) { - this.name = name; - this.email = email; +class InventoryRequesterV1 { + constructor() { + this.REQ_METHODS = ["HTTP"]; } - setTaxData(ssn, salary) { - this.taxData = new EmployeeTaxData(ssn, salary); + requestItem(item) { + // ... + } +} + +class InventoryRequesterV2 { + constructor() { + this.REQ_METHODS = ["WS"]; + } + + requestItem(item) { + // ... } - // ... } + +// By constructing our dependencies externally and injecting them, we can easily +// substitute our request module for a fancy new one that uses WebSockets. +const inventoryTracker = new InventoryTracker( + ["apples", "bananas"], + new InventoryRequesterV2() +); +inventoryTracker.requestItems(); ``` + **[⬆ 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 didn't break anything. Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) is how 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/). +[good coverage tool](https://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](https://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 @@ -1719,94 +1849,110 @@ 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', () => { +describe("MomentJS", () => { + it("handles date boundaries", () => { let date; - date = new MakeMomentJSGreatAgain('1/1/2015'); + date = new MomentJS("1/1/2015"); date.addDays(30); - date.shouldEqual('1/31/2015'); + assert.equal("1/31/2015", date); - date = new MakeMomentJSGreatAgain('2/1/2016'); + date = new MomentJS("2/1/2016"); date.addDays(28); - assert.equal('02/29/2016', date); + assert.equal("02/29/2016", date); - date = new MakeMomentJSGreatAgain('2/1/2015'); + date = new MomentJS("2/1/2015"); date.addDays(28); - assert.equal('03/01/2015', date); + assert.equal("03/01/2015", date); }); }); ``` **Good:** + ```javascript -const assert = require('assert'); +import assert from "assert"; -describe('MakeMomentJSGreatAgain', () => { - it('handles 30-day months', () => { - const date = new MakeMomentJSGreatAgain('1/1/2015'); +describe("MomentJS", () => { + it("handles 30-day months", () => { + const date = new MomentJS("1/1/2015"); date.addDays(30); - date.shouldEqual('1/31/2015'); + assert.equal("1/31/2015", date); }); - it('handles leap year', () => { - const date = new MakeMomentJSGreatAgain('2/1/2016'); + it("handles leap year", () => { + const date = new MomentJS("2/1/2016"); date.addDays(28); - assert.equal('02/29/2016', date); + assert.equal("02/29/2016", date); }); - it('handles non-leap year', () => { - const date = new MakeMomentJSGreatAgain('2/1/2015'); + it("handles non-leap year", () => { + const date = new MomentJS("2/1/2015"); date.addDays(28); - assert.equal('03/01/2015', date); + assert.equal("03/01/2015", date); }); }); ``` + **[⬆ back to top](#table-of-contents)** ## **Concurrency** + ### Use Promises, not 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) => { - if (requestErr) { - console.error(requestErr); - } else { - require('fs').writeFile('article.html', response.body, (writeErr) => { - if (writeErr) { - console.error(writeErr); - } else { - console.log('File written'); - } - }); +import { get } from "request"; +import { writeFile } from "fs"; + +get( + "https://en.wikipedia.org/wiki/Robert_Cecil_Martin", + (requestErr, response, body) => { + if (requestErr) { + console.error(requestErr); + } else { + writeFile("article.html", body, writeErr => { + if (writeErr) { + console.error(writeErr); + } else { + console.log("File written"); + } + }); + } } -}); - +); ``` **Good:** + ```javascript -require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') - .then((response) => { - return require('fs-promise').writeFile('article.html', response); +import { get } from "request-promise"; +import { writeFile } from "fs-extra"; + +get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") + .then(body => { + return writeFile("article.html", body); }) .then(() => { - console.log('File written'); + console.log("File written"); }) - .catch((err) => { + .catch(err => { console.error(err); }); - ``` + **[⬆ back to top](#table-of-contents)** ### Async/Await are even cleaner than Promises + Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await which offer an even cleaner solution. All you need is a function that is prefixed in an `async` keyword, and then you can write your logic imperatively without @@ -1814,42 +1960,55 @@ a `then` chain of functions. Use this if you can take advantage of ES2017/ES8 fe today! **Bad:** + ```javascript -require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin') - .then((response) => { - return require('fs-promise').writeFile('article.html', response); +import { get } from "request-promise"; +import { writeFile } from "fs-extra"; + +get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") + .then(body => { + return writeFile("article.html", body); }) .then(() => { - console.log('File written'); + console.log("File written"); }) - .catch((err) => { + .catch(err => { console.error(err); }); - ``` **Good:** + ```javascript +import { get } from "request-promise"; +import { writeFile } from "fs-extra"; + 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); - console.log('File written'); - } catch(err) { + const body = await get( + "https://en.wikipedia.org/wiki/Robert_Cecil_Martin" + ); + await writeFile("article.html", body); + console.log("File written"); + } catch (err) { console.error(err); } } + +getCleanCodeArticle() ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ back to top](#table-of-contents)** ## **Error Handling** + Thrown errors are a good thing! They mean the runtime has successfully 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 + 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 @@ -1858,6 +2017,7 @@ think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs. **Bad:** + ```javascript try { functionThatMightThrow(); @@ -1867,6 +2027,7 @@ try { ``` **Good:** + ```javascript try { functionThatMightThrow(); @@ -1882,44 +2043,47 @@ try { ``` ### Don't ignore 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)** - ## **Formatting** + Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is DO NOT ARGUE over formatting. -There are [tons of tools](http://standardjs.com/rules.html) to automate this. +There are [tons of tools](https://standardjs.com/rules.html) to automate this. Use one! It's a waste of time and money for engineers to argue over formatting. For things that don't fall under the purview of automatic formatting @@ -1927,17 +2091,19 @@ For things that don't fall under the purview of automatic formatting for some guidance. ### Use consistent capitalization + JavaScript is untyped, so capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just be consistent. **Bad:** + ```javascript const DAYS_IN_WEEK = 7; const daysInMonth = 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 restore_database() {} @@ -1947,12 +2113,13 @@ class Alpaca {} ``` **Good:** + ```javascript 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() {} @@ -1960,15 +2127,17 @@ function restoreDatabase() {} class Animal {} class Alpaca {} ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ back to top](#table-of-contents)** ### Function callers and callees should be close + 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. **Bad:** + ```javascript class PerformanceReview { constructor(employee) { @@ -1976,11 +2145,11 @@ class PerformanceReview { } lookupPeers() { - return db.lookup(this.employee, 'peers'); + return db.lookup(this.employee, "peers"); } lookupManager() { - return db.lookup(this.employee, 'manager'); + return db.lookup(this.employee, "manager"); } getPeerReviews() { @@ -2003,11 +2172,12 @@ class PerformanceReview { } } -const review = new PerformanceReview(user); +const review = new PerformanceReview(employee); review.perfReview(); ``` **Good:** + ```javascript class PerformanceReview { constructor(employee) { @@ -2026,7 +2196,7 @@ class PerformanceReview { } lookupPeers() { - return db.lookup(this.employee, 'peers'); + return db.lookup(this.employee, "peers"); } getManagerReview() { @@ -2034,7 +2204,7 @@ class PerformanceReview { } lookupManager() { - return db.lookup(this.employee, 'manager'); + return db.lookup(this.employee, "manager"); } getSelfReview() { @@ -2049,10 +2219,13 @@ review.perfReview(); **[⬆ back to top](#table-of-contents)** ## **Comments** + ### Only comment things that have business logic complexity. -Comments are an apology, not a requirement. Good code *mostly* documents itself. + +Comments are an apology, not a requirement. Good code _mostly_ documents itself. **Bad:** + ```javascript function hashIt(data) { // The hash @@ -2066,7 +2239,7 @@ function hashIt(data) { // Get character code. const char = data.charCodeAt(i); // Make the hash - hash = ((hash << 5) - hash) + char; + hash = (hash << 5) - hash + char; // Convert to 32-bit integer hash &= hash; } @@ -2074,28 +2247,30 @@ function hashIt(data) { ``` **Good:** -```javascript +```javascript function hashIt(data) { let hash = 0; const length = data.length; for (let i = 0; i < length; i++) { const char = data.charCodeAt(i); - hash = ((hash << 5) - hash) + char; + hash = (hash << 5) - hash + char; // Convert to 32-bit integer hash &= hash; } } - ``` + **[⬆ 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. **Bad:** + ```javascript doStuff(); // doOtherStuff(); @@ -2104,16 +2279,20 @@ doStuff(); ``` **Good:** + ```javascript doStuff(); ``` + **[⬆ back to top](#table-of-contents)** ### Don't have journal comments + Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Use `git log` to get history! **Bad:** + ```javascript /** * 2016-12-20: Removed monads, didn't understand them (RM) @@ -2127,25 +2306,29 @@ function combine(a, b) { ``` **Good:** + ```javascript function combine(a, b) { return a + b; } ``` + **[⬆ back to top](#table-of-contents)** ### Avoid positional markers + They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code. **Bad:** + ```javascript //////////////////////////////////////////////////////////////////////////////// // Scope Model Instantiation //////////////////////////////////////////////////////////////////////////////// $scope.model = { - menu: 'foo', - nav: 'bar' + menu: "foo", + nav: "bar" }; //////////////////////////////////////////////////////////////////////////////// @@ -2157,27 +2340,47 @@ const actions = function() { ``` **Good:** + ```javascript $scope.model = { - menu: 'foo', - nav: 'bar' + menu: "foo", + nav: "bar" }; const actions = function() { // ... }; ``` + **[⬆ back to top](#table-of-contents)** ## Translation 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) - - ![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/) - +- ![am](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Armenia.png) **Armenian**: [hanumanum/clean-code-javascript/](https://github.com/hanumanum/clean-code-javascript) +- ![bd](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Bangladesh.png) **Bangla(বাংলা)**: [InsomniacSabbir/clean-code-javascript/](https://github.com/InsomniacSabbir/clean-code-javascript/) +- ![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) **Simplified Chinese**: + - [alivebao/clean-code-js](https://github.com/alivebao/clean-code-js) + - [beginor/clean-code-javascript](https://github.com/beginor/clean-code-javascript) +- ![tw](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png) **Traditional Chinese**: [AllJointTW/clean-code-javascript](https://github.com/AllJointTW/clean-code-javascript) +- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [eugene-augier/clean-code-javascript-fr](https://github.com/eugene-augier/clean-code-javascript-fr) +- ![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) +- ![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/) +- ![it](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Italy.png) **Italian**: [frappacchio/clean-code-javascript/](https://github.com/frappacchio/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/) +- ![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) +- ![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) +- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [tureey/clean-code-javascript](https://github.com/tureey/clean-code-javascript) +- ![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) +- ![rs](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Serbia.png) **Serbian**: [doskovicmilos/clean-code-javascript/](https://github.com/doskovicmilos/clean-code-javascript) +- ![tr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Turkey.png) **Turkish**: [bsonmez/clean-code-javascript](https://github.com/bsonmez/clean-code-javascript/tree/turkish-translation) +- ![ua](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Ukraine.png) **Ukrainian**: [mindfr1k/clean-code-javascript-ua](https://github.com/mindfr1k/clean-code-javascript-ua) +- ![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/) +- ![ir](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Iran.png) **Persian**: [hamettio/clean-code-javascript](https://github.com/hamettio/clean-code-javascript) **[⬆ back to top](#table-of-contents)**