From 70cec497708933d004219e35271856488d436c64 Mon Sep 17 00:00:00 2001 From: ahmedmohmd Date: Sat, 18 Feb 2023 11:17:24 +0200 Subject: [PATCH 1/2] insert two topics to variables section --- README.md | 254 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 174 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index f1159781..c1aadd7b 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ Explicit is better than implicit. ```javascript const locations = ["Austin", "New York", "San Francisco"]; -locations.forEach(l => { +locations.forEach((l) => { doStuff(); doSomeOtherStuff(); // ... @@ -154,7 +154,7 @@ locations.forEach(l => { ```javascript const locations = ["Austin", "New York", "San Francisco"]; -locations.forEach(location => { +locations.forEach((location) => { doStuff(); doSomeOtherStuff(); // ... @@ -166,6 +166,103 @@ locations.forEach(location => { **[⬆ back to top](#table-of-contents)** +### Pick a One Word Per Concept + +The idea is to choose a single word or phrase that accurately and succinctly represents the concept or meaning of the variable, function, or class, and then use that same word consistently throughout the codebase. + +**Bad:** + +```javascript +const name = "Jonh"; +const age = 20; +const rank = 0.95; +``` + +**Good:** + +```javascript +const customerName = "Jonh"; +const customerAge = 20; +customerRank = 0.95; +``` + +**[⬆ back to top](#table-of-contents)** + +### Don’t Pun + +Puns mean words that have multiple meanings, These puns can make your code hard to read and understand, So to solve this problem try to use names that accurately represent the meaning or purpose of the variable. + +**Bad:** + +```javascript +class History { + constructor() { + this.urls = []; + } + + add(url) { + this.urls.push(url); + } +} + +class Book { + constructor() { + this.pages = []; + } + + add(page) { + this.page.push(page); + } +} +``` + +**Good:** + +```javascript +class History { + constructor() { + this.urls = []; + } + + addUrl(url) { + this.urls.push(url); + } +} + +class Book { + constructor() { + this.pages = []; + } + + addPage(page) { + this.page.push(page); + } +} + +// Another Solution: +class History { + constructor() { + this.urls = []; + } + + push(url) { + this.urls.push(url); + } +} + +class Book { + constructor() { + this.pages = []; + } + + insert(page) { + this.page.push(page); + } +} +``` + +**[⬆ 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 @@ -177,7 +274,7 @@ variable name. const Car = { carMake: "Honda", carModel: "Accord", - carColor: "Blue" + carColor: "Blue", }; function paintCar(car, color) { @@ -191,7 +288,7 @@ function paintCar(car, color) { const Car = { make: "Honda", model: "Accord", - color: "Blue" + color: "Blue", }; function paintCar(car, color) { @@ -267,7 +364,6 @@ function createMenu(title, body, buttonText, cancellable) { } createMenu("Foo", "Bar", "Baz", true); - ``` **Good:** @@ -281,7 +377,7 @@ createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", - cancellable: true + cancellable: true, }); ``` @@ -299,7 +395,7 @@ this guide other than this, you'll be ahead of many developers. ```javascript function emailClients(clients) { - clients.forEach(client => { + clients.forEach((client) => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); @@ -367,18 +463,18 @@ function parseBetterJSAlternative(code) { 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... }); } @@ -390,7 +486,7 @@ function parseBetterJSAlternative(code) { function parseBetterJSAlternative(code) { const tokens = tokenize(code); const syntaxTree = parse(tokens); - syntaxTree.forEach(node => { + syntaxTree.forEach((node) => { // parse... }); } @@ -402,8 +498,8 @@ function tokenize(code) { const statements = code.split(" "); const tokens = []; - REGEXES.forEach(REGEX => { - statements.forEach(statement => { + REGEXES.forEach((REGEX) => { + statements.forEach((statement) => { tokens.push(/* ... */); }); }); @@ -413,7 +509,7 @@ function tokenize(code) { function parse(tokens) { const syntaxTree = []; - tokens.forEach(token => { + tokens.forEach((token) => { syntaxTree.push(/* ... */); }); @@ -450,14 +546,14 @@ updating multiple places anytime you want to change one thing. ```javascript function showDeveloperList(developers) { - developers.forEach(developer => { + developers.forEach((developer) => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); const data = { expectedSalary, experience, - githubLink + githubLink, }; render(data); @@ -465,14 +561,14 @@ function showDeveloperList(developers) { } function showManagerList(managers) { - managers.forEach(manager => { + managers.forEach((manager) => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); const data = { expectedSalary, experience, - portfolio + portfolio, }; render(data); @@ -484,13 +580,13 @@ function showManagerList(managers) { ```javascript function showEmployeeList(employees) { - employees.forEach(employee => { + employees.forEach((employee) => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); const data = { expectedSalary, - experience + experience, }; switch (employee.type) { @@ -518,7 +614,7 @@ const menuConfig = { title: null, body: "Bar", buttonText: null, - cancellable: true + cancellable: true, }; function createMenu(config) { @@ -539,7 +635,7 @@ const menuConfig = { title: "Order", // User did not include 'body' key buttonText: "Send", - cancellable: true + cancellable: true, }; function createMenu(config) { @@ -548,11 +644,11 @@ function createMenu(config) { title: "Foo", body: "Bar", buttonText: "Baz", - cancellable: true + cancellable: true, }, config ); - return finalConfig + return finalConfig; // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ... } @@ -643,16 +739,16 @@ console.log(newName); // ['Ryan', 'McDermott']; ### Avoid Side Effects (part 2) -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 +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 +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 @@ -663,7 +759,7 @@ 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 the `cart` array was modified. -A great solution would be for the `addItemToCart` function to always clone the +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. @@ -714,7 +810,7 @@ would be much better to just use ES2015/ES6 classes and simply extend the `Array ```javascript Array.prototype.diff = function diff(comparisonArray) { const hash = new Set(comparisonArray); - return this.filter(elem => !hash.has(elem)); + return this.filter((elem) => !hash.has(elem)); }; ``` @@ -724,7 +820,7 @@ Array.prototype.diff = function diff(comparisonArray) { class SuperArray extends Array { diff(comparisonArray) { const hash = new Set(comparisonArray); - return this.filter(elem => !hash.has(elem)); + return this.filter((elem) => !hash.has(elem)); } } ``` @@ -743,20 +839,20 @@ Favor this style of programming when you can. const programmerOutput = [ { name: "Uncle Bobby", - linesOfCode: 500 + linesOfCode: 500, }, { name: "Suzie Q", - linesOfCode: 1500 + linesOfCode: 1500, }, { name: "Jimmy Gosling", - linesOfCode: 150 + linesOfCode: 150, }, { name: "Gracie Hopper", - linesOfCode: 1000 - } + linesOfCode: 1000, + }, ]; let totalOutput = 0; @@ -772,20 +868,20 @@ for (let i = 0; i < programmerOutput.length; i++) { const programmerOutput = [ { name: "Uncle Bobby", - linesOfCode: 500 + linesOfCode: 500, }, { name: "Suzie Q", - linesOfCode: 1500 + linesOfCode: 1500, }, { name: "Jimmy Gosling", - linesOfCode: 150 + linesOfCode: 150, }, { name: "Gracie Hopper", - linesOfCode: 1000 - } + linesOfCode: 1000, + }, ]; const totalOutput = programmerOutput.reduce( @@ -1059,7 +1155,7 @@ function makeBankAccount() { // ... return { - balance: 0 + balance: 0, // ... }; } @@ -1089,7 +1185,7 @@ function makeBankAccount() { return { // ... getBalance, - setBalance + setBalance, }; } @@ -1106,7 +1202,7 @@ This can be accomplished through closures (for ES5 and below). **Bad:** ```javascript -const Employee = function(name) { +const Employee = function (name) { this.name = name; }; @@ -1127,7 +1223,7 @@ function makeEmployee(name) { return { getName() { return name; - } + }, }; } @@ -1151,7 +1247,7 @@ classes until you find yourself needing larger and more complex objects. **Bad:** ```javascript -const Animal = function(age) { +const Animal = function (age) { if (!(this instanceof Animal)) { throw new Error("Instantiate Animal with `new`"); } @@ -1161,7 +1257,7 @@ const Animal = function(age) { Animal.prototype.move = function move() {}; -const Mammal = function(age, furColor) { +const Mammal = function (age, furColor) { if (!(this instanceof Mammal)) { throw new Error("Instantiate Mammal with `new`"); } @@ -1174,7 +1270,7 @@ Mammal.prototype = Object.create(Animal.prototype); Mammal.prototype.constructor = Mammal; Mammal.prototype.liveBirth = function liveBirth() {}; -const Human = function(age, furColor, languageSpoken) { +const Human = function (age, furColor, languageSpoken) { if (!(this instanceof Human)) { throw new Error("Instantiate Human with `new`"); } @@ -1469,11 +1565,11 @@ class HttpRequester { fetch(url) { if (this.adapter.name === "ajaxAdapter") { - return makeAjaxCall(url).then(response => { + return makeAjaxCall(url).then((response) => { // transform response and return }); } else if (this.adapter.name === "nodeAdapter") { - return makeHttpCall(url).then(response => { + return makeHttpCall(url).then((response) => { // transform response and return }); } @@ -1520,7 +1616,7 @@ class HttpRequester { } fetch(url) { - return this.adapter.request(url).then(response => { + return this.adapter.request(url).then((response) => { // transform response and return }); } @@ -1587,7 +1683,7 @@ class Square extends Rectangle { } function renderLargeRectangles(rectangles) { - rectangles.forEach(rectangle => { + rectangles.forEach((rectangle) => { rectangle.setWidth(4); rectangle.setHeight(5); const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. @@ -1636,7 +1732,7 @@ class Square extends Shape { } function renderLargeShapes(shapes) { - shapes.forEach(shape => { + shapes.forEach((shape) => { const area = shape.getArea(); shape.render(area); }); @@ -1685,7 +1781,7 @@ class DOMTraverser { const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), - animationModule() {} // Most of the time, we won't need to animate when traversing. + animationModule() {}, // Most of the time, we won't need to animate when traversing. // ... }); ``` @@ -1719,8 +1815,8 @@ class DOMTraverser { const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), options: { - animationModule() {} - } + animationModule() {}, + }, }); ``` @@ -1772,7 +1868,7 @@ class InventoryTracker { } requestItems() { - this.items.forEach(item => { + this.items.forEach((item) => { this.requester.requestItem(item); }); } @@ -1792,7 +1888,7 @@ class InventoryTracker { } requestItems() { - this.items.forEach(item => { + this.items.forEach((item) => { this.requester.requestItem(item); }); } @@ -1919,7 +2015,7 @@ get( if (requestErr) { console.error(requestErr); } else { - writeFile("article.html", body, writeErr => { + writeFile("article.html", body, (writeErr) => { if (writeErr) { console.error(writeErr); } else { @@ -1938,13 +2034,13 @@ import { get } from "request-promise"; import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") - .then(body => { + .then((body) => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) - .catch(err => { + .catch((err) => { console.error(err); }); ``` @@ -1966,13 +2062,13 @@ import { get } from "request-promise"; import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") - .then(body => { + .then((body) => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) - .catch(err => { + .catch((err) => { console.error(err); }); ``` @@ -1985,9 +2081,7 @@ import { writeFile } from "fs-extra"; async function getCleanCodeArticle() { try { - const body = await get( - "https://en.wikipedia.org/wiki/Robert_Cecil_Martin" - ); + const body = await get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin"); await writeFile("article.html", body); console.log("File written"); } catch (err) { @@ -1995,7 +2089,7 @@ async function getCleanCodeArticle() { } } -getCleanCodeArticle() +getCleanCodeArticle(); ``` **[⬆ back to top](#table-of-contents)** @@ -2051,10 +2145,10 @@ from `try/catch`. ```javascript getdata() - .then(data => { + .then((data) => { functionThatMightThrow(data); }) - .catch(error => { + .catch((error) => { console.log(error); }); ``` @@ -2063,10 +2157,10 @@ getdata() ```javascript getdata() - .then(data => { + .then((data) => { functionThatMightThrow(data); }) - .catch(error => { + .catch((error) => { // One option (more noisy than console.log): console.error(error); // Another option: @@ -2328,13 +2422,13 @@ proper indentation and formatting give the visual structure to your code. //////////////////////////////////////////////////////////////////////////////// $scope.model = { menu: "foo", - nav: "bar" + nav: "bar", }; //////////////////////////////////////////////////////////////////////////////// // Action setup //////////////////////////////////////////////////////////////////////////////// -const actions = function() { +const actions = function () { // ... }; ``` @@ -2344,10 +2438,10 @@ const actions = function() { ```javascript $scope.model = { menu: "foo", - nav: "bar" + nav: "bar", }; -const actions = function() { +const actions = function () { // ... }; ``` From 2c9cf9477c9ca864231764f2fdc6aad62b35495e Mon Sep 17 00:00:00 2001 From: ahmedmohmd Date: Sat, 18 Feb 2023 11:19:39 +0200 Subject: [PATCH 2/2] fix a bug in (Pick a One Word Per Concept) topic in Variables section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c1aadd7b..54541014 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ const rank = 0.95; ```javascript const customerName = "Jonh"; const customerAge = 20; -customerRank = 0.95; +const customerRank = 0.95; ``` **[⬆ back to top](#table-of-contents)**