├── .gitattributes ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-documentation=false 2 | *.md linguist-language=JavaScript 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Ryan McDermott 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clean-code-javascript 2 | 3 | ## Table of Contents 4 | 5 | 1. [Introduction](#introduction) 6 | 2. [Variables](#variables) 7 | 3. [Functions](#functions) 8 | 4. [Objects and Data Structures](#objects-and-data-structures) 9 | 5. [Classes](#classes) 10 | 6. [SOLID](#solid) 11 | 7. [Testing](#testing) 12 | 8. [Concurrency](#concurrency) 13 | 9. [Error Handling](#error-handling) 14 | 10. [Formatting](#formatting) 15 | 11. [Comments](#comments) 16 | 12. [Translation](#translation) 17 | 18 | ## Introduction 19 | 20 | ![Humorous image of software quality estimation as a count of how many expletives 21 | you shout when reading code](https://www.osnews.com/images/comics/wtfm.jpg) 22 | 23 | Software engineering principles, from Robert C. Martin's book 24 | [_Clean Code_](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), 25 | adapted for JavaScript. This is not a style guide. It's a guide to producing 26 | [readable, reusable, and refactorable](https://github.com/ryanmcdermott/3rs-of-software-architecture) software in JavaScript. 27 | 28 | اصول مهندسی نرم افزار، از کتاب رابرت سی مارتین 29 | _Clean Code_ سازگار با جاوا اسکریپت. این یک راهنمای سبک نیست. این راهنمای تولید نرم‌افزار قابل خواندن، قابل استفاده مجدد و قابل بازسازی در جاوا اسکریپت است. 30 | 31 | Not every principle herein has to be strictly followed, and even fewer will be 32 | universally agreed upon. These are guidelines and nothing more, but they are 33 | ones codified over many years of collective experience by the authors of 34 | _Clean Code_. 35 | 36 | لازم نیست همه اصول در اینجا به طور دقیق رعایت شوند، و حتی تعداد کمتری از آنها مورد توافق جهانی قرار خواهند گرفت. اینها دستورالعمل ها هستند و نه چیزی بیشتر، اما آنها دستورالعمل هایی هستند که طی سال ها تجربه جمعی توسط نویسندگان کتاب تدوین شده اند. 37 | 38 | Our craft of software engineering is just a bit over 50 years old, and we are 39 | still learning a lot. When software architecture is as old as architecture 40 | itself, maybe then we will have harder rules to follow. For now, let these 41 | guidelines serve as a touchstone by which to assess the quality of the 42 | JavaScript code that you and your team produce. 43 | 44 | پیشه ما در مهندسی نرم افزار کمی بیش از 50 سال قدمت دارد و ما هنوز در حال یادگیری چیزهای زیادی هستیم. وقتی معماری نرم‌افزار به قدمت خود معماری باشد، شاید قوانین سخت‌تری برای پیروی داشته باشیم. در حال حاضر، اجازه دهید این دستورالعمل ها به عنوان سنگ محک برای ارزیابی کیفیت کد جاوا اسکریپتی که شما و تیمتان تولید می کنید، عمل کنند. 45 | 46 | One more thing: knowing these won't immediately make you a better software 47 | developer, and working with them for many years doesn't mean you won't make 48 | mistakes. Every piece of code starts as a first draft, like wet clay getting 49 | shaped into its final form. Finally, we chisel away the imperfections when 50 | we review it with our peers. Don't beat yourself up for first drafts that need 51 | improvement. Beat up the code instead! 52 | 53 | یک چیز دیگر: دانستن این موارد فوراً شما را به یک توسعه‌دهنده نرم‌افزار بهتر تبدیل نمی‌کند، و کار کردن با آنها برای سال‌ها به این معنی نیست که اشتباه نخواهید کرد. هر قطعه کد به عنوان اولین پیش نویس شروع می شود، مانند خاک رس مرطوب که به شکل نهایی خود شکل می گیرد. در نهایت، هنگامی که آن را با همتایان خود مرور می کنیم، عیوب را از بین می بریم. برای اولین پیش نویس هایی که نیاز به بهبود دارند، خود را مورد ضرب و شتم قرار ندهید. در عوض کد را شکست دهید! 54 | 55 | ## **Variables** 56 | ## متغیرها 57 | ### Use meaningful and pronounceable variable names 58 | 59 | ### از نام متغیرهای معنی دار و قابل تلفظ استفاده کنید 60 | 61 | **Bad:** 62 | 63 | ```javascript 64 | const yyyymmdstr = moment().format("YYYY/MM/DD"); 65 | ``` 66 | 67 | **Good:** 68 | 69 | ```javascript 70 | const currentDate = moment().format("YYYY/MM/DD"); 71 | ``` 72 | 73 | **[⬆ back to top](#table-of-contents)** 74 | 75 | ### Use the same vocabulary for the same type of variable 76 | 77 | ### از واژگان یکسان برای همان نوع متغیر استفاده کنید 78 | **Bad:** 79 | 80 | ```javascript 81 | getUserInfo(); 82 | getClientData(); 83 | getCustomerRecord(); 84 | ``` 85 | 86 | **Good:** 87 | 88 | ```javascript 89 | getUser(); 90 | ``` 91 | 92 | **[⬆ back to top](#table-of-contents)** 93 | 94 | ### Use searchable names 95 | 96 | ### از اسامی قابل جستجو استفاده کنید 97 | 98 | We will read more code than we will ever write. It's important that the code we 99 | do write is readable and searchable. By _not_ naming variables that end up 100 | being meaningful for understanding our program, we hurt our readers. 101 | Make your names searchable. Tools like 102 | [buddy.js](https://github.com/danielstjules/buddy.js) and 103 | [ESLint](https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md) 104 | can help identify unnamed constants. 105 | 106 | ما بیشتر از آنچه که تا به حال بنویسیم کد می خوانیم. مهم است که کدی که می نویسیم قابل خواندن و جستجو باشد. با نام بردن از متغیرهایی که در نهایت برای درک برنامه ما معنادار هستند، به خوانندگان خود صدمه می زنیم. نام خود را قابل جستجو کنید ابزارهایی مانند buddy.js و ESLint می توانند به شناسایی ثابت های بدون نام کمک کنند. 107 | 108 | **Bad:** 109 | 110 | ```javascript 111 | // What the heck is 86400000 for? 112 | setTimeout(blastOff, 86400000); 113 | ``` 114 | 115 | **Good:** 116 | 117 | ```javascript 118 | // Declare them as capitalized named constants. 119 | const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000; 120 | 121 | setTimeout(blastOff, MILLISECONDS_PER_DAY); 122 | ``` 123 | 124 | **[⬆ back to top](#table-of-contents)** 125 | 126 | ### Use explanatory variables 127 | 128 | ### از متغیرهای توضیحی استفاده کنید 129 | 130 | **Bad:** 131 | 132 | ```javascript 133 | const address = "One Infinite Loop, Cupertino 95014"; 134 | const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 135 | saveCityZipCode( 136 | address.match(cityZipCodeRegex)[1], 137 | address.match(cityZipCodeRegex)[2] 138 | ); 139 | ``` 140 | 141 | **Good:** 142 | 143 | ```javascript 144 | const address = "One Infinite Loop, Cupertino 95014"; 145 | const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 146 | const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; 147 | saveCityZipCode(city, zipCode); 148 | ``` 149 | 150 | **[⬆ back to top](#table-of-contents)** 151 | 152 | ### Avoid Mental Mapping 153 | 154 | ### از نقشه برداری ذهنی خودداری کنید 155 | 156 | Explicit is better than implicit. 157 | 158 | صریح بهتر از ضمنی است. 159 | 160 | **Bad:** 161 | 162 | ```javascript 163 | const locations = ["Austin", "New York", "San Francisco"]; 164 | locations.forEach(l => { 165 | doStuff(); 166 | doSomeOtherStuff(); 167 | // ... 168 | // ... 169 | // ... 170 | // Wait, what is `l` for again? 171 | dispatch(l); 172 | }); 173 | ``` 174 | 175 | **Good:** 176 | 177 | ```javascript 178 | const locations = ["Austin", "New York", "San Francisco"]; 179 | locations.forEach(location => { 180 | doStuff(); 181 | doSomeOtherStuff(); 182 | // ... 183 | // ... 184 | // ... 185 | dispatch(location); 186 | }); 187 | ``` 188 | 189 | **[⬆ back to top](#table-of-contents)** 190 | 191 | ### Don't add unneeded context 192 | 193 | ### زمینه غیر ضروری را اضافه نکنید 194 | 195 | If your class/object name tells you something, don't repeat that in your 196 | variable name. 197 | 198 | اگر نام کلاس/شیء شما چیزی به شما می گوید، آن را در نام متغیر خود تکرار نکنید. 199 | 200 | **Bad:** 201 | 202 | ```javascript 203 | const Car = { 204 | carMake: "Honda", 205 | carModel: "Accord", 206 | carColor: "Blue" 207 | }; 208 | 209 | function paintCar(car, color) { 210 | car.carColor = color; 211 | } 212 | ``` 213 | 214 | **Good:** 215 | 216 | ```javascript 217 | const Car = { 218 | make: "Honda", 219 | model: "Accord", 220 | color: "Blue" 221 | }; 222 | 223 | function paintCar(car, color) { 224 | car.color = color; 225 | } 226 | ``` 227 | 228 | **[⬆ back to top](#table-of-contents)** 229 | 230 | ### Use default arguments instead of short circuiting or conditionals 231 | 232 | ### به جای اتصال کوتاه یا شرطی از آرگومان های پیش فرض استفاده کنید 233 | 234 | Default arguments are often cleaner than short circuiting. Be aware that if you 235 | use them, your function will only provide default values for `undefined` 236 | arguments. Other "falsy" values such as `''`, `""`, `false`, `null`, `0`, and 237 | `NaN`, will not be replaced by a default value. 238 | 239 | آرگومان های پیش فرض اغلب تمیزتر از اتصال کوتاه هستند. توجه داشته باشید که اگر از آنها استفاده کنید، تابع شما فقط مقادیر پیش فرض را برای آرگومان های « undefined» ارائه می دهد. سایر مقادیر "falsy" مانند """، """، "undefined"، "null"، "0" و "NaN" با یک مقدار پیش‌فرض جایگزین نمی‌شوند. 240 | 241 | **Bad:** 242 | 243 | ```javascript 244 | function createMicrobrewery(name) { 245 | const breweryName = name || "Hipster Brew Co."; 246 | // ... 247 | } 248 | ``` 249 | 250 | **Good:** 251 | 252 | ```javascript 253 | function createMicrobrewery(name = "Hipster Brew Co.") { 254 | // ... 255 | } 256 | ``` 257 | 258 | **[⬆ back to top](#table-of-contents)** 259 | 260 | ## **Functions** 261 | 262 | ## **توابع** 263 | 264 | ### Function arguments (2 or fewer ideally) 265 | 266 | ### آرگومان های تابع (در حالت ایده آل 2 یا کمتر) 267 | 268 | Limiting the amount of function parameters is incredibly important because it 269 | makes testing your function easier. Having more than three leads to a 270 | combinatorial explosion where you have to test tons of different cases with 271 | each separate argument. 272 | 273 | محدود کردن مقدار پارامترهای تابع بسیار مهم است زیرا آزمایش عملکرد شما را آسان‌تر می‌کند. داشتن بیش از سه مورد منجر به یک انفجار ترکیبی می شود که در آن باید هزاران مورد مختلف را با هر آرگومان جداگانه آزمایش کنید. 274 | 275 | One or two arguments is the ideal case, and three should be avoided if possible. 276 | Anything more than that should be consolidated. Usually, if you have 277 | more than two arguments then your function is trying to do too much. In cases 278 | where it's not, most of the time a higher-level object will suffice as an 279 | argument. 280 | 281 | یک یا دو استدلال حالت ایده آل است و در صورت امکان باید از سه استدلال اجتناب شود. هر چیزی بیش از این باید تجمیع شود. معمولاً، اگر بیش از دو آرگومان دارید، تابع شما تلاش می‌کند کارهای زیادی انجام دهد. در مواردی که اینطور نیست، اغلب اوقات یک شی سطح بالاتر به عنوان یک آرگومان کافی است. 282 | 283 | Since JavaScript allows you to make objects on the fly, without a lot of class 284 | boilerplate, you can use an object if you are finding yourself needing a 285 | lot of arguments. 286 | 287 | از آنجایی که جاوا اسکریپت به شما این امکان را می‌دهد که بدون استفاده از کلاس‌های زیاد، اشیا را بسازید، اگر متوجه شدید که به آرگومان‌های زیادی نیاز دارید، می‌توانید از یک شی استفاده کنید. 288 | 289 | To make it obvious what properties the function expects, you can use the ES2015/ES6 290 | destructuring syntax. This has a few advantages: 291 | 292 | برای اینکه مشخص شود تابع چه ویژگی هایی را انتظار دارد، می توانید از نحو ساختارشکنی ES2015/ES6 استفاده کنید. این چند مزیت دارد: 293 | 294 | 1. When someone looks at the function signature, it's immediately clear what 295 | properties are being used. 296 | 2. It can be used to simulate named parameters. 297 | 3. Destructuring also clones the specified primitive values of the argument 298 | object passed into the function. This can help prevent side effects. Note: 299 | objects and arrays that are destructured from the argument object are NOT 300 | cloned. 301 | 4. Linters can warn you about unused properties, which would be impossible 302 | without destructuring. 303 | 304 | 1. وقتی کسی به امضای تابع نگاه می کند، فوراً مشخص می شود که از چه ویژگی هایی استفاده می شود. 305 | 2. می توان از آن برای شبیه سازی پارامترهای نامگذاری شده استفاده کرد. 306 | 3. و Destructuring همچنین مقادیر اولیه مشخص شده شیء آرگومان ارسال شده به تابع را شبیه سازی می کند. این می تواند به جلوگیری از عوارض جانبی کمک کند. توجه: اشیاء و آرایه هایی که از شی آرگومان تخریب می شوند، کلون نمی شوند. 307 | 4. لینترها می توانند به شما در مورد خواص استفاده نشده هشدار دهند که بدون تخریب غیرممکن است. 308 | 309 | **Bad:** 310 | 311 | ```javascript 312 | function createMenu(title, body, buttonText, cancellable) { 313 | // ... 314 | } 315 | 316 | createMenu("Foo", "Bar", "Baz", true); 317 | 318 | ``` 319 | 320 | **Good:** 321 | 322 | ```javascript 323 | function createMenu({ title, body, buttonText, cancellable }) { 324 | // ... 325 | } 326 | 327 | createMenu({ 328 | title: "Foo", 329 | body: "Bar", 330 | buttonText: "Baz", 331 | cancellable: true 332 | }); 333 | ``` 334 | 335 | **[⬆ back to top](#table-of-contents)** 336 | 337 | ### Functions should do one thing 338 | 339 | ### توابع باید یک کار را انجام دهند 340 | 341 | This is by far the most important rule in software engineering. When functions 342 | do more than one thing, they are harder to compose, test, and reason about. 343 | When you can isolate a function to just one action, it can be refactored 344 | easily and your code will read much cleaner. If you take nothing else away from 345 | this guide other than this, you'll be ahead of many developers. 346 | 347 | این مهم ترین قانون در مهندسی نرم افزار است. وقتی توابع بیش از یک کار را انجام می دهند، نوشتن، آزمایش و استدلال در مورد آنها سخت تر است. وقتی می‌توانید یک تابع را فقط به یک عمل جدا کنید، می‌توانید آن را به راحتی دوباره فاکتور کنید و کد شما بسیار تمیزتر خوانده می‌شود. اگر به جز این چیز دیگری از این راهنما حذف نکنید، از بسیاری از توسعه دهندگان جلوتر خواهید بود. 348 | 349 | **Bad:** 350 | 351 | ```javascript 352 | function emailClients(clients) { 353 | clients.forEach(client => { 354 | const clientRecord = database.lookup(client); 355 | if (clientRecord.isActive()) { 356 | email(client); 357 | } 358 | }); 359 | } 360 | ``` 361 | 362 | **Good:** 363 | 364 | ```javascript 365 | function emailActiveClients(clients) { 366 | clients.filter(isActiveClient).forEach(email); 367 | } 368 | 369 | function isActiveClient(client) { 370 | const clientRecord = database.lookup(client); 371 | return clientRecord.isActive(); 372 | } 373 | ``` 374 | 375 | **[⬆ back to top](#table-of-contents)** 376 | 377 | ### Function names should say what they do 378 | 379 | ### نام توابع باید نشان دهند که چه کاری انجام می دهند 380 | 381 | **Bad:** 382 | 383 | ```javascript 384 | function addToDate(date, month) { 385 | // ... 386 | } 387 | 388 | const date = new Date(); 389 | 390 | // It's hard to tell from the function name what is added 391 | addToDate(date, 1); 392 | ``` 393 | 394 | **Good:** 395 | 396 | ```javascript 397 | function addMonthToDate(month, date) { 398 | // ... 399 | } 400 | 401 | const date = new Date(); 402 | addMonthToDate(1, date); 403 | ``` 404 | 405 | **[⬆ back to top](#table-of-contents)** 406 | 407 | ### Functions should only be one level of abstraction 408 | 409 | ### توابع باید فقط یک سطح از انتزاع باشند 410 | 411 | When you have more than one level of abstraction your function is usually 412 | doing too much. Splitting up functions leads to reusability and easier 413 | testing. 414 | 415 | وقتی بیش از یک سطح از انتزاع دارید، عملکرد شما معمولاً بیش از حد انجام می دهد. تقسیم توابع منجر به قابلیت استفاده مجدد و آزمایش آسان تر می شود. 416 | 417 | **Bad:** 418 | 419 | ```javascript 420 | function parseBetterJSAlternative(code) { 421 | const REGEXES = [ 422 | // ... 423 | ]; 424 | 425 | const statements = code.split(" "); 426 | const tokens = []; 427 | REGEXES.forEach(REGEX => { 428 | statements.forEach(statement => { 429 | // ... 430 | }); 431 | }); 432 | 433 | const ast = []; 434 | tokens.forEach(token => { 435 | // lex... 436 | }); 437 | 438 | ast.forEach(node => { 439 | // parse... 440 | }); 441 | } 442 | ``` 443 | 444 | **Good:** 445 | 446 | ```javascript 447 | function parseBetterJSAlternative(code) { 448 | const tokens = tokenize(code); 449 | const syntaxTree = parse(tokens); 450 | syntaxTree.forEach(node => { 451 | // parse... 452 | }); 453 | } 454 | 455 | function tokenize(code) { 456 | const REGEXES = [ 457 | // ... 458 | ]; 459 | 460 | const statements = code.split(" "); 461 | const tokens = []; 462 | REGEXES.forEach(REGEX => { 463 | statements.forEach(statement => { 464 | tokens.push(/* ... */); 465 | }); 466 | }); 467 | 468 | return tokens; 469 | } 470 | 471 | function parse(tokens) { 472 | const syntaxTree = []; 473 | tokens.forEach(token => { 474 | syntaxTree.push(/* ... */); 475 | }); 476 | 477 | return syntaxTree; 478 | } 479 | ``` 480 | 481 | **[⬆ back to top](#table-of-contents)** 482 | 483 | ### Remove duplicate code 484 | 485 | ### کد تکراری را حذف کنید 486 | Do your absolute best to avoid duplicate code. Duplicate code is bad because it 487 | means that there's more than one place to alter something if you need to change 488 | some logic. 489 | 490 | تمام تلاش خود را برای جلوگیری از کد تکراری انجام دهید. کد تکراری بد است زیرا به این معنی است که در صورت نیاز به تغییر منطق، بیش از یک مکان برای تغییر چیزی وجود دارد. 491 | 492 | Imagine if you run a restaurant and you keep track of your inventory: all your 493 | tomatoes, onions, garlic, spices, etc. If you have multiple lists that 494 | you keep this on, then all have to be updated when you serve a dish with 495 | tomatoes in them. If you only have one list, there's only one place to update! 496 | 497 | تصور کنید اگر رستورانی دارید و موجودی‌های خود را دنبال می‌کنید: همه گوجه‌فرنگی‌ها، پیاز، سیر، ادویه‌ها و غیره. اگر فهرست‌های متعددی دارید که این را در آن نگه می‌دارید، پس وقتی غذا با گوجه‌فرنگی سرو می‌کنید همه باید به‌روزرسانی شوند. اگر فقط یک لیست دارید، فقط یک مکان برای به روز رسانی وجود دارد! 498 | 499 | Oftentimes you have duplicate code because you have two or more slightly 500 | different things, that share a lot in common, but their differences force you 501 | to have two or more separate functions that do much of the same things. Removing 502 | duplicate code means creating an abstraction that can handle this set of 503 | different things with just one function/module/class. 504 | 505 | اغلب اوقات شما کد تکراری دارید زیرا دو یا چند چیز کمی متفاوت دارید که اشتراکات زیادی دارند، اما تفاوت‌های آنها شما را مجبور می‌کند دو یا چند تابع مجزا داشته باشید که بسیاری از کارهای مشابه را انجام می‌دهند. حذف کد تکراری به معنای ایجاد یک انتزاع است که بتواند این مجموعه از چیزهای مختلف را تنها با یک تابع/ماژول/کلاس مدیریت کند. 506 | 507 | Getting the abstraction right is critical, that's why you should follow the 508 | SOLID principles laid out in the _Classes_ section. Bad abstractions can be 509 | worse than duplicate code, so be careful! Having said this, if you can make 510 | a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself 511 | updating multiple places anytime you want to change one thing. 512 | 513 | درست کردن انتزاع بسیار مهم است، به همین دلیل است که باید از اصول SOLID که در بخش _Classes_ آمده است پیروی کنید. انتزاعات بد می توانند بدتر از کدهای تکراری باشند، پس مراقب باشید! با گفتن این، اگر می توانید یک انتزاع خوب بسازید، آن را انجام دهید! خودتان را تکرار نکنید، در غیر این صورت متوجه خواهید شد که هر زمان که بخواهید یک چیز را تغییر دهید چندین مکان را به روز می کنید. 514 | 515 | **Bad:** 516 | 517 | ```javascript 518 | function showDeveloperList(developers) { 519 | developers.forEach(developer => { 520 | const expectedSalary = developer.calculateExpectedSalary(); 521 | const experience = developer.getExperience(); 522 | const githubLink = developer.getGithubLink(); 523 | const data = { 524 | expectedSalary, 525 | experience, 526 | githubLink 527 | }; 528 | 529 | render(data); 530 | }); 531 | } 532 | 533 | function showManagerList(managers) { 534 | managers.forEach(manager => { 535 | const expectedSalary = manager.calculateExpectedSalary(); 536 | const experience = manager.getExperience(); 537 | const portfolio = manager.getMBAProjects(); 538 | const data = { 539 | expectedSalary, 540 | experience, 541 | portfolio 542 | }; 543 | 544 | render(data); 545 | }); 546 | } 547 | ``` 548 | 549 | **Good:** 550 | 551 | ```javascript 552 | function showEmployeeList(employees) { 553 | employees.forEach(employee => { 554 | const expectedSalary = employee.calculateExpectedSalary(); 555 | const experience = employee.getExperience(); 556 | 557 | const data = { 558 | expectedSalary, 559 | experience 560 | }; 561 | 562 | switch (employee.type) { 563 | case "manager": 564 | data.portfolio = employee.getMBAProjects(); 565 | break; 566 | case "developer": 567 | data.githubLink = employee.getGithubLink(); 568 | break; 569 | } 570 | 571 | render(data); 572 | }); 573 | } 574 | ``` 575 | 576 | **[⬆ back to top](#table-of-contents)** 577 | 578 | ### Set default objects with Object.assign 579 | 580 | ### اشیاء پیش فرض را با Object.assign تنظیم کنید 581 | 582 | **Bad:** 583 | 584 | ```javascript 585 | const menuConfig = { 586 | title: null, 587 | body: "Bar", 588 | buttonText: null, 589 | cancellable: true 590 | }; 591 | 592 | function createMenu(config) { 593 | config.title = config.title || "Foo"; 594 | config.body = config.body || "Bar"; 595 | config.buttonText = config.buttonText || "Baz"; 596 | config.cancellable = 597 | config.cancellable !== undefined ? config.cancellable : true; 598 | } 599 | 600 | createMenu(menuConfig); 601 | ``` 602 | 603 | **Good:** 604 | 605 | ```javascript 606 | const menuConfig = { 607 | title: "Order", 608 | // User did not include 'body' key 609 | buttonText: "Send", 610 | cancellable: true 611 | }; 612 | 613 | function createMenu(config) { 614 | let finalConfig = Object.assign( 615 | { 616 | title: "Foo", 617 | body: "Bar", 618 | buttonText: "Baz", 619 | cancellable: true 620 | }, 621 | config 622 | ); 623 | return finalConfig 624 | // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} 625 | // ... 626 | } 627 | 628 | createMenu(menuConfig); 629 | ``` 630 | 631 | **[⬆ back to top](#table-of-contents)** 632 | 633 | ### Don't use flags as function parameters 634 | 635 | ### از پرچم ها به عنوان پارامترهای تابع استفاده نکنید 636 | 637 | 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. 638 | 639 | رچم ها به کاربر شما می گویند که این تابع بیش از یک کار را انجام می دهد. توابع باید یک کار را انجام دهند. اگر توابع خود را بر اساس یک بولی مسیرهای کد متفاوتی را دنبال می کنند، تقسیم کنید. 640 | 641 | **Bad:** 642 | 643 | ```javascript 644 | function createFile(name, temp) { 645 | if (temp) { 646 | fs.create(`./temp/${name}`); 647 | } else { 648 | fs.create(name); 649 | } 650 | } 651 | ``` 652 | 653 | **Good:** 654 | 655 | ```javascript 656 | function createFile(name) { 657 | fs.create(name); 658 | } 659 | 660 | function createTempFile(name) { 661 | createFile(`./temp/${name}`); 662 | } 663 | ``` 664 | 665 | **[⬆ back to top](#table-of-contents)** 666 | 667 | ### Avoid Side Effects (part 1) 668 | 669 | ### اجتناب از عوارض جانبی (قسمت 1) 670 | 671 | A function produces a side effect if it does anything other than take a value in 672 | and return another value or values. A side effect could be writing to a file, 673 | modifying some global variable, or accidentally wiring all your money to a 674 | stranger. 675 | 676 | یک تابع اگر کاری غیر از دریافت مقدار و برگرداندن مقدار یا مقادیر دیگری انجام دهد، یک اثر جانبی ایجاد می کند. یک عارضه جانبی می تواند نوشتن در یک فایل، تغییر برخی از متغیرهای سراسری یا انتقال تصادفی تمام پول خود به یک غریبه باشد. 677 | 678 | Now, you do need to have side effects in a program on occasion. Like the previous 679 | example, you might need to write to a file. What you want to do is to 680 | centralize where you are doing this. Don't have several functions and classes 681 | that write to a particular file. Have one service that does it. One and only one. 682 | 683 | در حال حاضر، شما نیاز به عوارض جانبی در یک برنامه گاهی اوقات دارید. مانند مثال قبلی، ممکن است لازم باشد در یک فایل بنویسید. کاری که می خواهید انجام دهید این است که در جایی که این کار را انجام می دهید متمرکز شوید. چندین توابع و کلاس که در یک فایل خاص بنویسند ندارند. یک سرویس داشته باشید که این کار را انجام دهد. یک و تنها یکی. 684 | 685 | The main point is to avoid common pitfalls like sharing state between objects 686 | without any structure, using mutable data types that can be written to by anything, 687 | and not centralizing where your side effects occur. If you can do this, you will 688 | be happier than the vast majority of other programmers. 689 | 690 | نکته اصلی این است که از تله‌های رایج مانند اشتراک‌گذاری حالت بین اشیا بدون هیچ ساختاری، استفاده از انواع داده‌های قابل تغییر که می‌توانند توسط هر چیزی روی آن نوشته شوند، و تمرکز نکردن مکان‌هایی که عوارض جانبی شما رخ می‌دهند، اجتناب کنید. اگر بتوانید این کار را انجام دهید، از اکثریت قریب به اتفاق برنامه نویسان دیگر خوشحال خواهید شد. 691 | 692 | **Bad:** 693 | 694 | ```javascript 695 | // Global variable referenced by following function. 696 | // If we had another function that used this name, now it'd be an array and it could break it. 697 | let name = "Ryan McDermott"; 698 | 699 | function splitIntoFirstAndLastName() { 700 | name = name.split(" "); 701 | } 702 | 703 | splitIntoFirstAndLastName(); 704 | 705 | console.log(name); // ['Ryan', 'McDermott']; 706 | ``` 707 | 708 | **Good:** 709 | 710 | ```javascript 711 | function splitIntoFirstAndLastName(name) { 712 | return name.split(" "); 713 | } 714 | 715 | const name = "Ryan McDermott"; 716 | const newName = splitIntoFirstAndLastName(name); 717 | 718 | console.log(name); // 'Ryan McDermott'; 719 | console.log(newName); // ['Ryan', 'McDermott']; 720 | ``` 721 | 722 | **[⬆ back to top](#table-of-contents)** 723 | 724 | ### Avoid Side Effects (part 2) 725 | 726 | ### اجتناب از عوارض جانبی (قسمت 2) 727 | 728 | In JavaScript, some values are unchangeable (immutable) and some are changeable 729 | (mutable). Objects and arrays are two kinds of mutable values so it's important 730 | to handle them carefully when they're passed as parameters to a function. A 731 | JavaScript function can change an object's properties or alter the contents of 732 | an array which could easily cause bugs elsewhere. 733 | 734 | در جاوا اسکریپت، برخی از مقادیر غیرقابل تغییر (تغییرناپذیر) و برخی قابل تغییر (تغییرپذیر) هستند. اشیا و آرایه ها دو نوع مقدار قابل تغییر هستند، بنابراین مهم است که وقتی به عنوان پارامتر به یک تابع منتقل می شوند، آنها را با دقت مدیریت کنید. یک تابع جاوا اسکریپت می تواند ویژگی های یک شی را تغییر دهد یا محتویات یک آرایه را تغییر دهد که به راحتی می تواند باعث ایجاد اشکال در جاهای دیگر شود. 735 | 736 | Suppose there's a function that accepts an array parameter representing a 737 | shopping cart. If the function makes a change in that shopping cart array - 738 | by adding an item to purchase, for example - then any other function that 739 | uses that same `cart` array will be affected by this addition. That may be 740 | great, however it could also be bad. Let's imagine a bad situation: 741 | 742 | فرض کنید تابعی وجود دارد که پارامتر آرایه ای را که نشان دهنده سبد خرید است می پذیرد. اگر تابع تغییری در آرایه سبد خرید ایجاد کند - برای مثال با افزودن یک کالا برای خرید - هر تابع دیگری که از همان آرایه «سبد خرید» استفاده می‌کند تحت تأثیر این اضافه قرار می‌گیرد. ممکن است عالی باشد، با این حال ممکن است بد هم باشد. بیایید یک وضعیت بد را تصور کنیم: 743 | 744 | The user clicks the "Purchase" button which calls a `purchase` function that 745 | spawns a network request and sends the `cart` array to the server. Because 746 | of a bad network connection, the `purchase` function has to keep retrying the 747 | request. Now, what if in the meantime the user accidentally clicks an "Add to Cart" 748 | button on an item they don't actually want before the network request begins? 749 | If that happens and the network request begins, then that purchase function 750 | will send the accidentally added item because the `cart` array was modified. 751 | 752 | کاربر روی دکمه «خرید» کلیک می‌کند که تابع «خرید» را فراخوانی می‌کند که یک درخواست شبکه ایجاد می‌کند و آرایه «سبد خرید» را به سرور می‌فرستد. به دلیل اتصال شبکه بد، تابع «خرید» باید درخواست را دوباره امتحان کند. حال، اگر در این فاصله زمانی کاربر به طور تصادفی دکمه «افزودن به سبد خرید» را روی کالایی که واقعاً نمی‌خواهد، قبل از شروع درخواست شبکه کلیک کند، چه؟ 753 | اگر این اتفاق بیفتد و درخواست شبکه شروع شود، آن تابع خرید موردی که تصادفاً اضافه شده را ارسال می کند زیرا آرایه «سبد خرید» اصلاح شده است 754 | 755 | A great solution would be for the `addItemToCart` function to always clone the 756 | `cart`, edit it, and return the clone. This would ensure that functions that are still 757 | using the old shopping cart wouldn't be affected by the changes. 758 | 759 | یک راه حل عالی این است که تابع «addItemToCart» همیشه «سبد خرید» را شبیه سازی کند، آن را ویرایش کند و کلون را برگرداند. این تضمین می کند که عملکردهایی که هنوز از سبد خرید قدیمی استفاده می کنند تحت تأثیر تغییرات قرار نخواهند گرفت 760 | 761 | Two caveats to mention to this approach: 762 | 763 | دو اخطار برای ذکر این رویکرد 764 | 765 | 1. There might be cases where you actually want to modify the input object, 766 | but when you adopt this programming practice you will find that those cases 767 | are pretty rare. Most things can be refactored to have no side effects! 768 | 769 | 1. ممکن است مواردی وجود داشته باشد که شما واقعاً بخواهید شی ورودی را تغییر دهید، اما وقتی این روش برنامه نویسی را اتخاذ می کنید، متوجه می شوید که این موارد بسیار نادر هستند. بسیاری از چیزها را می توان بازسازی کرد تا هیچ عارضه ای نداشته باشد! 770 | 771 | 2. Cloning big objects can be very expensive in terms of performance. Luckily, 772 | this isn't a big issue in practice because there are 773 | [great libraries](https://facebook.github.io/immutable-js/) that allow 774 | this kind of programming approach to be fast and not as memory intensive as 775 | it would be for you to manually clone objects and arrays. 776 | 777 | 2. شبیه سازی اشیاء بزرگ می تواند از نظر عملکرد بسیار گران باشد. خوشبختانه، این در عمل مشکل بزرگی نیست، زیرا کتابخانه‌های بزرگی وجود دارند که به این نوع رویکرد برنامه‌نویسی اجازه می‌دهند سریع باشد و آنقدر حافظه فشرده نباشد که شما به صورت دستی اشیا و آرایه‌ها را شبیه‌سازی کنید. 778 | 779 | **Bad:** 780 | 781 | ```javascript 782 | const addItemToCart = (cart, item) => { 783 | cart.push({ item, date: Date.now() }); 784 | }; 785 | ``` 786 | 787 | **Good:** 788 | 789 | ```javascript 790 | const addItemToCart = (cart, item) => { 791 | return [...cart, { item, date: Date.now() }]; 792 | }; 793 | ``` 794 | 795 | **[⬆ back to top](#table-of-contents)** 796 | 797 | ### Don't write to global functions 798 | 799 | ### روی توابع جهانی ننویسید 800 | 801 | Polluting globals is a bad practice in JavaScript because you could clash with another 802 | library and the user of your API would be none-the-wiser until they get an 803 | exception in production. Let's think about an example: what if you wanted to 804 | extend JavaScript's native Array method to have a `diff` method that could 805 | show the difference between two arrays? You could write your new function 806 | to the `Array.prototype`, but it could clash with another library that tried 807 | to do the same thing. What if that other library was just using `diff` to find 808 | the difference between the first and last elements of an array? This is why it 809 | would be much better to just use ES2015/ES6 classes and simply extend the `Array` global. 810 | 811 | آلاینده کردن جهانی ها یک روش بد در جاوا اسکریپت است زیرا ممکن است با کتابخانه دیگری برخورد کنید و کاربر API شما عاقل تر نخواهد بود تا زمانی که در تولید استثنا پیدا کند. بیایید به یک مثال فکر کنیم: اگر بخواهید روش آرایه اصلی جاوا اسکریپت را گسترش دهید تا یک متد 'diff' داشته باشید که بتواند تفاوت بین دو آرایه را نشان دهد، چه؟ می‌توانید تابع جدید خود را در «Array.prototype» بنویسید، اما می‌تواند با کتابخانه دیگری که تلاش کرده است تداخل داشته باشد. 812 | برای انجام همین کار اگر آن کتابخانه دیگر فقط از "diff" برای یافتن تفاوت بین اولین و آخرین عناصر یک آرایه استفاده می کرد، چه می شد؟ به همین دلیل است که بهتر است فقط از کلاس های ES2015/ES6 استفاده کنیم و به سادگی "آرایه" را جهانی کنیم. 813 | 814 | **Bad:** 815 | 816 | ```javascript 817 | Array.prototype.diff = function diff(comparisonArray) { 818 | const hash = new Set(comparisonArray); 819 | return this.filter(elem => !hash.has(elem)); 820 | }; 821 | ``` 822 | 823 | **Good:** 824 | 825 | ```javascript 826 | class SuperArray extends Array { 827 | diff(comparisonArray) { 828 | const hash = new Set(comparisonArray); 829 | return this.filter(elem => !hash.has(elem)); 830 | } 831 | } 832 | ``` 833 | 834 | **[⬆ back to top](#table-of-contents)** 835 | 836 | ### Favor functional programming over imperative programming 837 | 838 | ### برنامه نویسی تابعی را بر برنامه نویسی ضروری ترجیح دهید 839 | 840 | JavaScript isn't a functional language in the way that Haskell is, but it has 841 | a functional flavor to it. Functional languages can be cleaner and easier to test. 842 | Favor this style of programming when you can. 843 | 844 | جاوا اسکریپت یک زبان کاربردی مانند Haskell نیست، اما طعمی کاربردی دارد. زبان‌های کاربردی می‌توانند تمیزتر و آسان‌تر برای آزمایش باشند. در صورت امکان از این سبک برنامه نویسی استفاده کنید. 845 | **Bad:** 846 | 847 | ```javascript 848 | const programmerOutput = [ 849 | { 850 | name: "Uncle Bobby", 851 | linesOfCode: 500 852 | }, 853 | { 854 | name: "Suzie Q", 855 | linesOfCode: 1500 856 | }, 857 | { 858 | name: "Jimmy Gosling", 859 | linesOfCode: 150 860 | }, 861 | { 862 | name: "Gracie Hopper", 863 | linesOfCode: 1000 864 | } 865 | ]; 866 | 867 | let totalOutput = 0; 868 | 869 | for (let i = 0; i < programmerOutput.length; i++) { 870 | totalOutput += programmerOutput[i].linesOfCode; 871 | } 872 | ``` 873 | 874 | **Good:** 875 | 876 | ```javascript 877 | const programmerOutput = [ 878 | { 879 | name: "Uncle Bobby", 880 | linesOfCode: 500 881 | }, 882 | { 883 | name: "Suzie Q", 884 | linesOfCode: 1500 885 | }, 886 | { 887 | name: "Jimmy Gosling", 888 | linesOfCode: 150 889 | }, 890 | { 891 | name: "Gracie Hopper", 892 | linesOfCode: 1000 893 | } 894 | ]; 895 | 896 | const totalOutput = programmerOutput.reduce( 897 | (totalLines, output) => totalLines + output.linesOfCode, 898 | 0 899 | ); 900 | ``` 901 | 902 | **[⬆ back to top](#table-of-contents)** 903 | 904 | ### Encapsulate conditionals 905 | 906 | **Bad:** 907 | 908 | ```javascript 909 | if (fsm.state === "fetching" && isEmpty(listNode)) { 910 | // ... 911 | } 912 | ``` 913 | 914 | **Good:** 915 | 916 | ```javascript 917 | function shouldShowSpinner(fsm, listNode) { 918 | return fsm.state === "fetching" && isEmpty(listNode); 919 | } 920 | 921 | if (shouldShowSpinner(fsmInstance, listNodeInstance)) { 922 | // ... 923 | } 924 | ``` 925 | 926 | **[⬆ back to top](#table-of-contents)** 927 | 928 | ### Avoid negative conditionals 929 | 930 | **Bad:** 931 | 932 | ```javascript 933 | function isDOMNodeNotPresent(node) { 934 | // ... 935 | } 936 | 937 | if (!isDOMNodeNotPresent(node)) { 938 | // ... 939 | } 940 | ``` 941 | 942 | **Good:** 943 | 944 | ```javascript 945 | function isDOMNodePresent(node) { 946 | // ... 947 | } 948 | 949 | if (isDOMNodePresent(node)) { 950 | // ... 951 | } 952 | ``` 953 | 954 | **[⬆ back to top](#table-of-contents)** 955 | 956 | ### Avoid conditionals 957 | 958 | ### از شرطی شدن بپرهیزید 959 | 960 | This seems like an impossible task. Upon first hearing this, most people say, 961 | "how am I supposed to do anything without an `if` statement?" The answer is that 962 | you can use polymorphism to achieve the same task in many cases. The second 963 | question is usually, "well that's great but why would I want to do that?" The 964 | answer is a previous clean code concept we learned: a function should only do 965 | one thing. When you have classes and functions that have `if` statements, you 966 | are telling your user that your function does more than one thing. Remember, 967 | just do one thing. 968 | 969 | این یک کار غیر ممکن به نظر می رسد. با اولین شنیدن این حرف، اکثر مردم می گویند، "چطور قرار است کاری را بدون عبارت "اگر" انجام دهم؟ پاسخ این است که در بسیاری از موارد می توانید از چندشکلی برای رسیدن به همان کار استفاده کنید. سؤال دوم معمولاً این است: "خوب این عالی است، اما چرا من می خواهم این کار را انجام دهم؟" پاسخ یک مفهوم کد تمیز قبلی است که یاد گرفتیم: یک تابع فقط باید انجام دهد 970 | یک چیز. وقتی کلاس‌ها و توابعی دارید که عبارت «if» دارند، به کاربر خود می‌گویید که تابع شما بیش از یک کار را انجام می‌دهد. به یاد داشته باشید، فقط یک کار را انجام دهید. 971 | 972 | **Bad:** 973 | 974 | ```javascript 975 | class Airplane { 976 | // ... 977 | getCruisingAltitude() { 978 | switch (this.type) { 979 | case "777": 980 | return this.getMaxAltitude() - this.getPassengerCount(); 981 | case "Air Force One": 982 | return this.getMaxAltitude(); 983 | case "Cessna": 984 | return this.getMaxAltitude() - this.getFuelExpenditure(); 985 | } 986 | } 987 | } 988 | ``` 989 | 990 | **Good:** 991 | 992 | ```javascript 993 | class Airplane { 994 | // ... 995 | } 996 | 997 | class Boeing777 extends Airplane { 998 | // ... 999 | getCruisingAltitude() { 1000 | return this.getMaxAltitude() - this.getPassengerCount(); 1001 | } 1002 | } 1003 | 1004 | class AirForceOne extends Airplane { 1005 | // ... 1006 | getCruisingAltitude() { 1007 | return this.getMaxAltitude(); 1008 | } 1009 | } 1010 | 1011 | class Cessna extends Airplane { 1012 | // ... 1013 | getCruisingAltitude() { 1014 | return this.getMaxAltitude() - this.getFuelExpenditure(); 1015 | } 1016 | } 1017 | ``` 1018 | 1019 | **[⬆ back to top](#table-of-contents)** 1020 | 1021 | ### Avoid type-checking (part 1) 1022 | 1023 | ### از بررسی نوع خودداری کنید (قسمت 1) 1024 | 1025 | JavaScript is untyped, which means your functions can take any type of argument. 1026 | Sometimes you are bitten by this freedom and it becomes tempting to do 1027 | type-checking in your functions. There are many ways to avoid having to do this. 1028 | The first thing to consider is consistent APIs. 1029 | 1030 | جاوا اسکریپت بدون تایپ است، به این معنی که توابع شما می توانند هر نوع آرگومان را بگیرند. 1031 | گاهی اوقات شما توسط این آزادی گاز گرفته می شوید و انجام چک کردن تایپ در عملکردهای خود وسوسه انگیز می شود. راه های زیادی برای اجتناب از انجام این کار وجود دارد. اولین چیزی که باید در نظر بگیرید API های سازگار است. 1032 | 1033 | **Bad:** 1034 | 1035 | ```javascript 1036 | function travelToTexas(vehicle) { 1037 | if (vehicle instanceof Bicycle) { 1038 | vehicle.pedal(this.currentLocation, new Location("texas")); 1039 | } else if (vehicle instanceof Car) { 1040 | vehicle.drive(this.currentLocation, new Location("texas")); 1041 | } 1042 | } 1043 | ``` 1044 | 1045 | **Good:** 1046 | 1047 | ```javascript 1048 | function travelToTexas(vehicle) { 1049 | vehicle.move(this.currentLocation, new Location("texas")); 1050 | } 1051 | ``` 1052 | 1053 | **[⬆ back to top](#table-of-contents)** 1054 | 1055 | ### Avoid type-checking (part 2) 1056 | 1057 | ### از بررسی نوع خودداری کنید (قسمت 2) 1058 | 1059 | If you are working with basic primitive values like strings and integers, 1060 | and you can't use polymorphism but you still feel the need to type-check, 1061 | you should consider using TypeScript. It is an excellent alternative to normal 1062 | JavaScript, as it provides you with static typing on top of standard JavaScript 1063 | syntax. The problem with manually type-checking normal JavaScript is that 1064 | doing it well requires so much extra verbiage that the faux "type-safety" you get 1065 | doesn't make up for the lost readability. Keep your JavaScript clean, write 1066 | good tests, and have good code reviews. Otherwise, do all of that but with 1067 | TypeScript (which, like I said, is a great alternative!). 1068 | 1069 | اگر با مقادیر اولیه اولیه مانند رشته ها و اعداد صحیح کار می کنید، 1070 | و شما نمی توانید از چند شکلی استفاده کنید، اما همچنان نیاز به بررسی تایپ دارید، باید از TypeScript استفاده کنید. این یک جایگزین عالی برای جاوا اسکریپت معمولی است، زیرا تایپ ایستا را در بالای نحو استاندارد جاوا اسکریپت برای شما فراهم می کند. مشکل چک کردن دستی تایپ جاوا اسکریپت معمولی این است که انجام آن به خوبی نیاز به پرگویی اضافی دارد که "ایمنی نوع" اشتباهی که دریافت می کنید خوانایی از دست رفته را جبران نمی کند. جاوا اسکریپت خود را تمیز نگه دارید، تست های خوبی بنویسید و کدهای خوبی را بررسی کنید. در غیر این صورت، همه این کارها را انجام دهید اما با TypeScript (که همانطور که گفتم جایگزین عالی است!). 1071 | 1072 | 1073 | **Bad:** 1074 | 1075 | ```javascript 1076 | function combine(val1, val2) { 1077 | if ( 1078 | (typeof val1 === "number" && typeof val2 === "number") || 1079 | (typeof val1 === "string" && typeof val2 === "string") 1080 | ) { 1081 | return val1 + val2; 1082 | } 1083 | 1084 | throw new Error("Must be of type String or Number"); 1085 | } 1086 | ``` 1087 | 1088 | **Good:** 1089 | 1090 | ```javascript 1091 | function combine(val1, val2) { 1092 | return val1 + val2; 1093 | } 1094 | ``` 1095 | 1096 | **[⬆ back to top](#table-of-contents)** 1097 | 1098 | ### Don't over-optimize 1099 | ### بیش از حد بهینه سازی نکنید 1100 | 1101 | Modern browsers do a lot of optimization under-the-hood at runtime. A lot of 1102 | times, if you are optimizing then you are just wasting your time. [There are good 1103 | resources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) 1104 | for seeing where optimization is lacking. Target those in the meantime, until 1105 | they are fixed if they can be. 1106 | 1107 | مرورگرهای مدرن در زمان اجرا بهینه سازی های زیادی را در پایین صفحه انجام می دهند. در بسیاری از مواقع، اگر در حال بهینه سازی هستید، فقط وقت خود را تلف می کنید. خوب وجود دارد 1108 | منابع برای دیدن جایی که بهینه سازی وجود ندارد. در این بین آن‌ها را مورد هدف قرار دهید، تا زمانی که در صورت امکان برطرف شوند. 1109 | 1110 | **Bad:** 1111 | 1112 | ```javascript 1113 | // On old browsers, each iteration with uncached `list.length` would be costly 1114 | // because of `list.length` recomputation. In modern browsers, this is optimized. 1115 | for (let i = 0, len = list.length; i < len; i++) { 1116 | // ... 1117 | } 1118 | ``` 1119 | 1120 | **Good:** 1121 | 1122 | ```javascript 1123 | for (let i = 0; i < list.length; i++) { 1124 | // ... 1125 | } 1126 | ``` 1127 | 1128 | **[⬆ back to top](#table-of-contents)** 1129 | 1130 | ### Remove dead code 1131 | ### کد مرده را حذف کنید 1132 | 1133 | Dead code is just as bad as duplicate code. There's no reason to keep it in 1134 | your codebase. If it's not being called, get rid of it! It will still be safe 1135 | in your version history if you still need it. 1136 | 1137 | کد مرده به اندازه کد تکراری بد است. دلیلی وجود ندارد که آن را در پایگاه کد خود نگه دارید. اگر نامیده نمی شود، از شر آن خلاص شوید! اگر همچنان به آن نیاز دارید، همچنان در تاریخچه نسخه شما ایمن خواهد بود. 1138 | 1139 | **Bad:** 1140 | 1141 | ```javascript 1142 | function oldRequestModule(url) { 1143 | // ... 1144 | } 1145 | 1146 | function newRequestModule(url) { 1147 | // ... 1148 | } 1149 | 1150 | const req = newRequestModule; 1151 | inventoryTracker("apples", req, "www.inventory-awesome.io"); 1152 | ``` 1153 | 1154 | **Good:** 1155 | 1156 | ```javascript 1157 | function newRequestModule(url) { 1158 | // ... 1159 | } 1160 | 1161 | const req = newRequestModule; 1162 | inventoryTracker("apples", req, "www.inventory-awesome.io"); 1163 | ``` 1164 | 1165 | **[⬆ back to top](#table-of-contents)** 1166 | 1167 | ## **Objects and Data Structures** 1168 | 1169 | ## **اشیاء و ساختارهای داده** 1170 | 1171 | ### Use getters and setters 1172 | 1173 | ### از getter و setterها استفاده کنید 1174 | 1175 | Using getters and setters to access data on objects could be better than simply 1176 | looking for a property on an object. "Why?" you might ask. Well, here's an 1177 | unorganized list of reasons why: 1178 | 1179 | استفاده از گیرنده‌ها و تنظیم‌کننده‌ها برای دسترسی به داده‌های روی اشیا می‌تواند بهتر از جستجوی ساده یک ویژگی روی یک شی باشد. "چرا؟" ممکن است بپرسید خوب، در اینجا یک لیست سازمان نیافته از دلایل وجود دارد: 1180 | 1181 | - When you want to do more beyond getting an object property, you don't have 1182 | to look up and change every accessor in your codebase. 1183 | - Makes adding validation simple when doing a `set`. 1184 | - Encapsulates the internal representation. 1185 | - Easy to add logging and error handling when getting and setting. 1186 | - You can lazy load your object's properties, let's say getting it from a 1187 | server. 1188 | 1189 | - هنگامی که می خواهید کارهای بیشتری فراتر از دریافت ویژگی شی انجام دهید، لازم نیست به دنبال جستجو و تغییر هر دسترسی در پایگاه کد خود باشید. 1190 | - افزودن اعتبارسنجی را هنگام انجام یک «مجموعه» ساده می کند. 1191 | - نمایش داخلی را کپسوله می کند. 1192 | - اضافه کردن ورود به سیستم و مدیریت خطا هنگام دریافت و تنظیم آسان است. 1193 | - می توانید ویژگی های شیء خود را با تنبلی بارگذاری کنید، فرض کنید آن را از a دریافت کنید 1194 | سرور 1195 | 1196 | **Bad:** 1197 | 1198 | ```javascript 1199 | function makeBankAccount() { 1200 | // ... 1201 | 1202 | return { 1203 | balance: 0 1204 | // ... 1205 | }; 1206 | } 1207 | 1208 | const account = makeBankAccount(); 1209 | account.balance = 100; 1210 | ``` 1211 | 1212 | **Good:** 1213 | 1214 | ```javascript 1215 | function makeBankAccount() { 1216 | // this one is private 1217 | let balance = 0; 1218 | 1219 | // a "getter", made public via the returned object below 1220 | function getBalance() { 1221 | return balance; 1222 | } 1223 | 1224 | // a "setter", made public via the returned object below 1225 | function setBalance(amount) { 1226 | // ... validate before updating the balance 1227 | balance = amount; 1228 | } 1229 | 1230 | return { 1231 | // ... 1232 | getBalance, 1233 | setBalance 1234 | }; 1235 | } 1236 | 1237 | const account = makeBankAccount(); 1238 | account.setBalance(100); 1239 | ``` 1240 | 1241 | **[⬆ back to top](#table-of-contents)** 1242 | 1243 | ### Make objects have private members 1244 | 1245 | ### اشیاء را دارای اعضای خصوصی کنید 1246 | 1247 | This can be accomplished through closures (for ES5 and below). 1248 | 1249 | این را می توان از طریق بسته شدن (برای ES5 و پایین تر) انجام داد. 1250 | 1251 | **Bad:** 1252 | 1253 | ```javascript 1254 | const Employee = function(name) { 1255 | this.name = name; 1256 | }; 1257 | 1258 | Employee.prototype.getName = function getName() { 1259 | return this.name; 1260 | }; 1261 | 1262 | const employee = new Employee("John Doe"); 1263 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 1264 | delete employee.name; 1265 | console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined 1266 | ``` 1267 | 1268 | **Good:** 1269 | 1270 | ```javascript 1271 | function makeEmployee(name) { 1272 | return { 1273 | getName() { 1274 | return name; 1275 | } 1276 | }; 1277 | } 1278 | 1279 | const employee = makeEmployee("John Doe"); 1280 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 1281 | delete employee.name; 1282 | console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 1283 | ``` 1284 | 1285 | **[⬆ back to top](#table-of-contents)** 1286 | 1287 | ## **Classes** 1288 | 1289 | ## **کلاس ها** 1290 | 1291 | ### Prefer ES2015/ES6 classes over ES5 plain functions 1292 | 1293 | ### کلاس های ES2015/ES6 را به توابع ساده ES5 ترجیح دهید 1294 | 1295 | It's very difficult to get readable class inheritance, construction, and method 1296 | definitions for classical ES5 classes. If you need inheritance (and be aware 1297 | that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over 1298 | classes until you find yourself needing larger and more complex objects. 1299 | 1300 | بدست آوردن وراثت کلاس، ساخت و تعاریف متد قابل خواندن برای کلاس های کلاسیک ES5 بسیار دشوار است. اگر به ارث نیاز دارید (و توجه داشته باشید که ممکن است نباشید)، کلاس های ES2015/ES6 را ترجیح دهید. با این حال، توابع کوچک را به کلاس ها ترجیح دهید تا زمانی که متوجه شوید که به اشیاء بزرگتر و پیچیده تر نیاز دارید. 1301 | 1302 | **Bad:** 1303 | 1304 | ```javascript 1305 | const Animal = function(age) { 1306 | if (!(this instanceof Animal)) { 1307 | throw new Error("Instantiate Animal with `new`"); 1308 | } 1309 | 1310 | this.age = age; 1311 | }; 1312 | 1313 | Animal.prototype.move = function move() {}; 1314 | 1315 | const Mammal = function(age, furColor) { 1316 | if (!(this instanceof Mammal)) { 1317 | throw new Error("Instantiate Mammal with `new`"); 1318 | } 1319 | 1320 | Animal.call(this, age); 1321 | this.furColor = furColor; 1322 | }; 1323 | 1324 | Mammal.prototype = Object.create(Animal.prototype); 1325 | Mammal.prototype.constructor = Mammal; 1326 | Mammal.prototype.liveBirth = function liveBirth() {}; 1327 | 1328 | const Human = function(age, furColor, languageSpoken) { 1329 | if (!(this instanceof Human)) { 1330 | throw new Error("Instantiate Human with `new`"); 1331 | } 1332 | 1333 | Mammal.call(this, age, furColor); 1334 | this.languageSpoken = languageSpoken; 1335 | }; 1336 | 1337 | Human.prototype = Object.create(Mammal.prototype); 1338 | Human.prototype.constructor = Human; 1339 | Human.prototype.speak = function speak() {}; 1340 | ``` 1341 | 1342 | **Good:** 1343 | 1344 | ```javascript 1345 | class Animal { 1346 | constructor(age) { 1347 | this.age = age; 1348 | } 1349 | 1350 | move() { 1351 | /* ... */ 1352 | } 1353 | } 1354 | 1355 | class Mammal extends Animal { 1356 | constructor(age, furColor) { 1357 | super(age); 1358 | this.furColor = furColor; 1359 | } 1360 | 1361 | liveBirth() { 1362 | /* ... */ 1363 | } 1364 | } 1365 | 1366 | class Human extends Mammal { 1367 | constructor(age, furColor, languageSpoken) { 1368 | super(age, furColor); 1369 | this.languageSpoken = languageSpoken; 1370 | } 1371 | 1372 | speak() { 1373 | /* ... */ 1374 | } 1375 | } 1376 | ``` 1377 | 1378 | **[⬆ back to top](#table-of-contents)** 1379 | 1380 | ### Use method chaining 1381 | 1382 | ### از روش زنجیره ای استفاده کنید 1383 | 1384 | This pattern is very useful in JavaScript and you see it in many libraries such 1385 | as jQuery and Lodash. It allows your code to be expressive, and less verbose. 1386 | For that reason, I say, use method chaining and take a look at how clean your code 1387 | will be. In your class functions, simply return `this` at the end of every function, 1388 | and you can chain further class methods onto it. 1389 | 1390 | این الگو در جاوا اسکریپت بسیار کاربردی است و آن را در بسیاری از کتابخانه ها مانند jQuery و Lodash مشاهده می کنید. این اجازه می دهد تا کد شما رسا، و کمتر پرمخاطب باشد. به همین دلیل، من می گویم، از روش زنجیره ای استفاده کنید و به پاک بودن کد خود نگاه کنید. در توابع کلاس خود، به سادگی «this» را در انتهای هر تابع برگردانید، و می توانید متدهای کلاس بیشتری را به آن زنجیره بزنید. 1391 | 1392 | **Bad:** 1393 | 1394 | ```javascript 1395 | class Car { 1396 | constructor(make, model, color) { 1397 | this.make = make; 1398 | this.model = model; 1399 | this.color = color; 1400 | } 1401 | 1402 | setMake(make) { 1403 | this.make = make; 1404 | } 1405 | 1406 | setModel(model) { 1407 | this.model = model; 1408 | } 1409 | 1410 | setColor(color) { 1411 | this.color = color; 1412 | } 1413 | 1414 | save() { 1415 | console.log(this.make, this.model, this.color); 1416 | } 1417 | } 1418 | 1419 | const car = new Car("Ford", "F-150", "red"); 1420 | car.setColor("pink"); 1421 | car.save(); 1422 | ``` 1423 | 1424 | **Good:** 1425 | 1426 | ```javascript 1427 | class Car { 1428 | constructor(make, model, color) { 1429 | this.make = make; 1430 | this.model = model; 1431 | this.color = color; 1432 | } 1433 | 1434 | setMake(make) { 1435 | this.make = make; 1436 | // NOTE: Returning this for chaining 1437 | return this; 1438 | } 1439 | 1440 | setModel(model) { 1441 | this.model = model; 1442 | // NOTE: Returning this for chaining 1443 | return this; 1444 | } 1445 | 1446 | setColor(color) { 1447 | this.color = color; 1448 | // NOTE: Returning this for chaining 1449 | return this; 1450 | } 1451 | 1452 | save() { 1453 | console.log(this.make, this.model, this.color); 1454 | // NOTE: Returning this for chaining 1455 | return this; 1456 | } 1457 | } 1458 | 1459 | const car = new Car("Ford", "F-150", "red").setColor("pink").save(); 1460 | ``` 1461 | 1462 | **[⬆ back to top](#table-of-contents)** 1463 | 1464 | ### Prefer composition over inheritance 1465 | 1466 | ### ترکیب را بر وراثت ترجیح دهید 1467 | 1468 | As stated famously in [_Design Patterns_](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, 1469 | you should prefer composition over inheritance where you can. There are lots of 1470 | good reasons to use inheritance and lots of good reasons to use composition. 1471 | The main point for this maxim is that if your mind instinctively goes for 1472 | inheritance, try to think if composition could model your problem better. In some 1473 | cases it can. 1474 | 1475 | همانطور که در _Design Patterns_ توسط باند چهار بیان شده است، 1476 | شما باید ترکیب را به ارث در جایی که می توانید ترجیح دهید. دلایل خوبی برای استفاده از وراثت و دلایل خوب زیادی برای استفاده از ترکیب وجود دارد. نکته اصلی برای این اصل این است که اگر ذهن شما به طور غریزی به سمت ارث می رود، سعی کنید فکر کنید که آیا ترکیب می تواند مشکل شما را بهتر مدل کند. در برخی موارد می تواند. 1477 | 1478 | You might be wondering then, "when should I use inheritance?" It 1479 | depends on your problem at hand, but this is a decent list of when inheritance 1480 | makes more sense than composition: 1481 | 1482 | ممکن است از خود بپرسید که "چه زمانی باید از ارث استفاده کنم؟" 1483 | این به مشکل شما بستگی دارد، اما این لیست مناسبی است از زمانی که وراثت بیشتر از ترکیب منطقی است: 1484 | 1485 | 1486 | 1. Your inheritance represents an "is-a" relationship and not a "has-a" 1487 | relationship (Human->Animal vs. User->UserDetails). 1488 | 2. You can reuse code from the base classes (Humans can move like all animals). 1489 | 3. You want to make global changes to derived classes by changing a base class. 1490 | (Change the caloric expenditure of all animals when they move). 1491 | 1492 | 1. وراثت شما نشان دهنده یک رابطه "is-a" است و نه "has-a" 1493 | رابطه (انسان-> حیوان در مقابل کاربر-> جزئیات کاربر). 1494 | 2. می توانید از کدهای کلاس های پایه مجددا استفاده کنید (انسان ها می توانند مانند همه حیوانات حرکت کنند). 1495 | 3. می خواهید با تغییر یک کلاس پایه، تغییرات سراسری در کلاس های مشتق شده ایجاد کنید. (مصرف کالری همه حیوانات را هنگام حرکت تغییر دهید). 1496 | 1497 | **Bad:** 1498 | 1499 | ```javascript 1500 | class Employee { 1501 | constructor(name, email) { 1502 | this.name = name; 1503 | this.email = email; 1504 | } 1505 | 1506 | // ... 1507 | } 1508 | 1509 | // Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee 1510 | class EmployeeTaxData extends Employee { 1511 | constructor(ssn, salary) { 1512 | super(); 1513 | this.ssn = ssn; 1514 | this.salary = salary; 1515 | } 1516 | 1517 | // ... 1518 | } 1519 | ``` 1520 | 1521 | **Good:** 1522 | 1523 | ```javascript 1524 | class EmployeeTaxData { 1525 | constructor(ssn, salary) { 1526 | this.ssn = ssn; 1527 | this.salary = salary; 1528 | } 1529 | 1530 | // ... 1531 | } 1532 | 1533 | class Employee { 1534 | constructor(name, email) { 1535 | this.name = name; 1536 | this.email = email; 1537 | } 1538 | 1539 | setTaxData(ssn, salary) { 1540 | this.taxData = new EmployeeTaxData(ssn, salary); 1541 | } 1542 | // ... 1543 | } 1544 | ``` 1545 | 1546 | **[⬆ back to top](#table-of-contents)** 1547 | 1548 | ## **SOLID** 1549 | 1550 | ### Single Responsibility Principle (SRP) 1551 | 1552 | ### اصل مسئولیت واحد (SRP) 1553 | 1554 | As stated in Clean Code, "There should never be more than one reason for a class 1555 | to change". It's tempting to jam-pack a class with a lot of functionality, like 1556 | when you can only take one suitcase on your flight. The issue with this is 1557 | that your class won't be conceptually cohesive and it will give it many reasons 1558 | to change. Minimizing the amount of times you need to change a class is important. 1559 | It's important because if too much functionality is in one class and you modify 1560 | a piece of it, it can be difficult to understand how that will affect other 1561 | dependent modules in your codebase. 1562 | 1563 | همانطور که در Clean Code گفته شد، "هرگز نباید بیش از یک دلیل برای تغییر کلاس وجود داشته باشد". وسوسه انگیز است که یک کلاس را با کارایی زیاد جمع کنید، مانند زمانی که فقط می توانید یک چمدان را در پرواز خود ببرید. مشکل این است که کلاس شما از نظر مفهومی منسجم نخواهد بود و دلایل زیادی برای تغییر به آن می دهد. به حداقل رساندن تعداد دفعاتی که برای تغییر کلاس نیاز دارید مهم است. 1564 | این مهم است زیرا اگر عملکرد بیش از حد در یک کلاس وجود دارد و شما بخشی از آن را تغییر می‌دهید، درک اینکه چگونه بر دیگر ماژول‌های وابسته در پایگاه کد شما تأثیر می‌گذارد دشوار است. 1565 | 1566 | **Bad:** 1567 | 1568 | ```javascript 1569 | class UserSettings { 1570 | constructor(user) { 1571 | this.user = user; 1572 | } 1573 | 1574 | changeSettings(settings) { 1575 | if (this.verifyCredentials()) { 1576 | // ... 1577 | } 1578 | } 1579 | 1580 | verifyCredentials() { 1581 | // ... 1582 | } 1583 | } 1584 | ``` 1585 | 1586 | **Good:** 1587 | 1588 | ```javascript 1589 | class UserAuth { 1590 | constructor(user) { 1591 | this.user = user; 1592 | } 1593 | 1594 | verifyCredentials() { 1595 | // ... 1596 | } 1597 | } 1598 | 1599 | class UserSettings { 1600 | constructor(user) { 1601 | this.user = user; 1602 | this.auth = new UserAuth(user); 1603 | } 1604 | 1605 | changeSettings(settings) { 1606 | if (this.auth.verifyCredentials()) { 1607 | // ... 1608 | } 1609 | } 1610 | } 1611 | ``` 1612 | 1613 | **[⬆ back to top](#table-of-contents)** 1614 | 1615 | ### Open/Closed Principle (OCP) 1616 | 1617 | ### اصل باز/بسته (OCP) 1618 | 1619 | As stated by Bertrand Meyer, "software entities (classes, modules, functions, 1620 | etc.) should be open for extension, but closed for modification." What does that 1621 | mean though? This principle basically states that you should allow users to 1622 | add new functionalities without changing existing code. 1623 | 1624 | همانطور که برتراند مایر بیان کرد، "موجودات نرم افزاری (کلاس ها، ماژول ها، توابع و غیره) باید برای توسعه باز باشند، اما برای اصلاح بسته شوند." با این حال این به چه معناست؟ این اصل اساسا بیان می کند که باید به کاربران اجازه دهید تا بدون تغییر کد موجود، قابلیت های جدیدی را اضافه کنند. 1625 | 1626 | **Bad:** 1627 | 1628 | ```javascript 1629 | class AjaxAdapter extends Adapter { 1630 | constructor() { 1631 | super(); 1632 | this.name = "ajaxAdapter"; 1633 | } 1634 | } 1635 | 1636 | class NodeAdapter extends Adapter { 1637 | constructor() { 1638 | super(); 1639 | this.name = "nodeAdapter"; 1640 | } 1641 | } 1642 | 1643 | class HttpRequester { 1644 | constructor(adapter) { 1645 | this.adapter = adapter; 1646 | } 1647 | 1648 | fetch(url) { 1649 | if (this.adapter.name === "ajaxAdapter") { 1650 | return makeAjaxCall(url).then(response => { 1651 | // transform response and return 1652 | }); 1653 | } else if (this.adapter.name === "nodeAdapter") { 1654 | return makeHttpCall(url).then(response => { 1655 | // transform response and return 1656 | }); 1657 | } 1658 | } 1659 | } 1660 | 1661 | function makeAjaxCall(url) { 1662 | // request and return promise 1663 | } 1664 | 1665 | function makeHttpCall(url) { 1666 | // request and return promise 1667 | } 1668 | ``` 1669 | 1670 | **Good:** 1671 | 1672 | ```javascript 1673 | class AjaxAdapter extends Adapter { 1674 | constructor() { 1675 | super(); 1676 | this.name = "ajaxAdapter"; 1677 | } 1678 | 1679 | request(url) { 1680 | // request and return promise 1681 | } 1682 | } 1683 | 1684 | class NodeAdapter extends Adapter { 1685 | constructor() { 1686 | super(); 1687 | this.name = "nodeAdapter"; 1688 | } 1689 | 1690 | request(url) { 1691 | // request and return promise 1692 | } 1693 | } 1694 | 1695 | class HttpRequester { 1696 | constructor(adapter) { 1697 | this.adapter = adapter; 1698 | } 1699 | 1700 | fetch(url) { 1701 | return this.adapter.request(url).then(response => { 1702 | // transform response and return 1703 | }); 1704 | } 1705 | } 1706 | ``` 1707 | 1708 | **[⬆ back to top](#table-of-contents)** 1709 | 1710 | ### Liskov Substitution Principle (LSP) 1711 | 1712 | ### اصل جایگزینی لیسکوف (LSP) 1713 | 1714 | This is a scary term for a very simple concept. It's formally defined as "If S 1715 | is a subtype of T, then objects of type T may be replaced with objects of type S 1716 | (i.e., objects of type S may substitute objects of type T) without altering any 1717 | of the desirable properties of that program (correctness, task performed, 1718 | etc.)." That's an even scarier definition. 1719 | 1720 | The best explanation for this is if you have a parent class and a child class, 1721 | then the base class and child class can be used interchangeably without getting 1722 | incorrect results. This might still be confusing, so let's take a look at the 1723 | classic Square-Rectangle example. Mathematically, a square is a rectangle, but 1724 | if you model it using the "is-a" relationship via inheritance, you quickly 1725 | get into trouble. 1726 | 1727 | این یک اصطلاح ترسناک برای یک مفهوم بسیار ساده است. به طور رسمی به این صورت تعریف می‌شود: «اگر S یک زیرگروه از T باشد، آنگاه اشیای نوع T ممکن است با اشیایی از نوع S جایگزین شوند (یعنی اشیاء نوع S ممکن است جایگزین اشیاء نوع T شوند) بدون تغییر هیچ یک از ویژگی‌های مطلوب آن برنامه. (صحت، کار انجام شده، و غیره)." این تعریف حتی ترسناک تر است. 1728 | بهترین توضیح برای این موضوع این است که اگر یک کلاس والد و یک کلاس فرزند دارید، کلاس پایه و کلاس فرزند را می توان به جای هم استفاده کرد بدون اینکه نتایج نادرستی دریافت کنید. این ممکن است هنوز گیج کننده باشد، بنابراین بیایید نگاهی به مثال کلاسیک مربع-مستطیل بیندازیم. از نظر ریاضی، مربع یک مستطیل است، اما اگر آن را با استفاده از رابطه "is-a" از طریق وراثت مدل کنید، به سرعت دچار مشکل می شوید. 1729 | 1730 | **Bad:** 1731 | 1732 | ```javascript 1733 | class Rectangle { 1734 | constructor() { 1735 | this.width = 0; 1736 | this.height = 0; 1737 | } 1738 | 1739 | setColor(color) { 1740 | // ... 1741 | } 1742 | 1743 | render(area) { 1744 | // ... 1745 | } 1746 | 1747 | setWidth(width) { 1748 | this.width = width; 1749 | } 1750 | 1751 | setHeight(height) { 1752 | this.height = height; 1753 | } 1754 | 1755 | getArea() { 1756 | return this.width * this.height; 1757 | } 1758 | } 1759 | 1760 | class Square extends Rectangle { 1761 | setWidth(width) { 1762 | this.width = width; 1763 | this.height = width; 1764 | } 1765 | 1766 | setHeight(height) { 1767 | this.width = height; 1768 | this.height = height; 1769 | } 1770 | } 1771 | 1772 | function renderLargeRectangles(rectangles) { 1773 | rectangles.forEach(rectangle => { 1774 | rectangle.setWidth(4); 1775 | rectangle.setHeight(5); 1776 | const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. 1777 | rectangle.render(area); 1778 | }); 1779 | } 1780 | 1781 | const rectangles = [new Rectangle(), new Rectangle(), new Square()]; 1782 | renderLargeRectangles(rectangles); 1783 | ``` 1784 | 1785 | **Good:** 1786 | 1787 | ```javascript 1788 | class Shape { 1789 | setColor(color) { 1790 | // ... 1791 | } 1792 | 1793 | render(area) { 1794 | // ... 1795 | } 1796 | } 1797 | 1798 | class Rectangle extends Shape { 1799 | constructor(width, height) { 1800 | super(); 1801 | this.width = width; 1802 | this.height = height; 1803 | } 1804 | 1805 | getArea() { 1806 | return this.width * this.height; 1807 | } 1808 | } 1809 | 1810 | class Square extends Shape { 1811 | constructor(length) { 1812 | super(); 1813 | this.length = length; 1814 | } 1815 | 1816 | getArea() { 1817 | return this.length * this.length; 1818 | } 1819 | } 1820 | 1821 | function renderLargeShapes(shapes) { 1822 | shapes.forEach(shape => { 1823 | const area = shape.getArea(); 1824 | shape.render(area); 1825 | }); 1826 | } 1827 | 1828 | const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; 1829 | renderLargeShapes(shapes); 1830 | ``` 1831 | 1832 | **[⬆ back to top](#table-of-contents)** 1833 | 1834 | ### Interface Segregation Principle (ISP) 1835 | 1836 | ### اصل جداسازی رابط (ISP) 1837 | 1838 | JavaScript doesn't have interfaces so this principle doesn't apply as strictly 1839 | as others. However, it's important and relevant even with JavaScript's lack of 1840 | type system. 1841 | 1842 | ISP states that "Clients should not be forced to depend upon interfaces that 1843 | they do not use." Interfaces are implicit contracts in JavaScript because of 1844 | duck typing. 1845 | 1846 | A good example to look at that demonstrates this principle in JavaScript is for 1847 | classes that require large settings objects. Not requiring clients to setup 1848 | huge amounts of options is beneficial, because most of the time they won't need 1849 | all of the settings. Making them optional helps prevent having a 1850 | "fat interface". 1851 | 1852 | جاوا اسکریپت رابط ندارد، بنابراین این اصل به سختی سایر اصول اعمال نمی شود. با این حال، حتی با عدم وجود سیستم نوع جاوا اسکریپت، مهم و مرتبط است. 1853 | 1854 | ISP بیان می کند که "کلینت ها نباید مجبور شوند به واسط هایی که استفاده نمی کنند وابسته شوند." اینترفیس ها قراردادهای ضمنی در جاوا اسکریپت به دلیل تایپ اردک هستند. 1855 | 1856 | یک مثال خوب که این اصل را در جاوا اسکریپت نشان می دهد برای کلاس هایی است که به اشیاء تنظیمات بزرگ نیاز دارند. عدم نیاز به مشتریان برای تنظیم مقادیر زیادی از گزینه ها مفید است، زیرا اکثر اوقات آنها به همه تنظیمات نیاز ندارند. اختیاری کردن آنها به جلوگیری از داشتن "رابط چربی" کمک می کند. 1857 | 1858 | **Bad:** 1859 | 1860 | ```javascript 1861 | class DOMTraverser { 1862 | constructor(settings) { 1863 | this.settings = settings; 1864 | this.setup(); 1865 | } 1866 | 1867 | setup() { 1868 | this.rootNode = this.settings.rootNode; 1869 | this.settings.animationModule.setup(); 1870 | } 1871 | 1872 | traverse() { 1873 | // ... 1874 | } 1875 | } 1876 | 1877 | const $ = new DOMTraverser({ 1878 | rootNode: document.getElementsByTagName("body"), 1879 | animationModule() {} // Most of the time, we won't need to animate when traversing. 1880 | // ... 1881 | }); 1882 | ``` 1883 | 1884 | **Good:** 1885 | 1886 | ```javascript 1887 | class DOMTraverser { 1888 | constructor(settings) { 1889 | this.settings = settings; 1890 | this.options = settings.options; 1891 | this.setup(); 1892 | } 1893 | 1894 | setup() { 1895 | this.rootNode = this.settings.rootNode; 1896 | this.setupOptions(); 1897 | } 1898 | 1899 | setupOptions() { 1900 | if (this.options.animationModule) { 1901 | // ... 1902 | } 1903 | } 1904 | 1905 | traverse() { 1906 | // ... 1907 | } 1908 | } 1909 | 1910 | const $ = new DOMTraverser({ 1911 | rootNode: document.getElementsByTagName("body"), 1912 | options: { 1913 | animationModule() {} 1914 | } 1915 | }); 1916 | ``` 1917 | 1918 | **[⬆ back to top](#table-of-contents)** 1919 | 1920 | ### Dependency Inversion Principle (DIP) 1921 | 1922 | ### اصل وارونگی وابستگی (DIP) 1923 | 1924 | This principle states two essential things: 1925 | 1926 | 1. High-level modules should not depend on low-level modules. Both should 1927 | depend on abstractions. 1928 | 2. Abstractions should not depend upon details. Details should depend on 1929 | abstractions. 1930 | 1931 | این اصل دو چیز اساسی را بیان می کند: 1932 | 1933 | 1. ماژول های سطح بالا نباید به ماژول های سطح پایین وابسته باشند. هر دو باید به انتزاعات بستگی داشته باشند. 1934 | 2. انتزاع ها نباید به جزئیات بستگی داشته باشند. جزئیات باید به انتزاعات بستگی داشته باشد. 1935 | 1936 | 1937 | This can be hard to understand at first, but if you've worked with AngularJS, 1938 | you've seen an implementation of this principle in the form of Dependency 1939 | Injection (DI). While they are not identical concepts, DIP keeps high-level 1940 | modules from knowing the details of its low-level modules and setting them up. 1941 | It can accomplish this through DI. A huge benefit of this is that it reduces 1942 | the coupling between modules. Coupling is a very bad development pattern because 1943 | it makes your code hard to refactor. 1944 | 1945 | درک این موضوع در ابتدا ممکن است سخت باشد، اما اگر با AngularJS کار کرده باشید، اجرای این اصل را در قالب Dependency Injection (DI) مشاهده کرده اید. در حالی که آنها مفاهیم یکسانی نیستند، DIP ماژول های سطح بالا را از دانستن جزئیات ماژول های سطح پایین خود و تنظیم آنها جلوگیری می کند. می تواند این کار را از طریق DI انجام دهد. یک مزیت بزرگ این است که جفت شدن بین ماژول ها را کاهش می دهد. کوپلینگ یک الگوی توسعه بسیار بد است، زیرا باعث می‌شود کد شما به‌سختی تغییر داده شود. 1946 | 1947 | As stated previously, JavaScript doesn't have interfaces so the abstractions 1948 | that are depended upon are implicit contracts. That is to say, the methods 1949 | and properties that an object/class exposes to another object/class. In the 1950 | example below, the implicit contract is that any Request module for an 1951 | `InventoryTracker` will have a `requestItems` method. 1952 | 1953 | همانطور که قبلاً گفته شد، جاوا اسکریپت واسط ندارد، بنابراین انتزاعاتی که به آنها وابسته هستند، قراردادهای ضمنی هستند. یعنی روش ها و ویژگی هایی که یک شی/کلاس در معرض شی/کلاس دیگر قرار می دهد. در مثال زیر، قرارداد ضمنی این است که هر ماژول درخواست برای «InventoryTracker» یک متد «requestItems» خواهد داشت. 1954 | 1955 | **Bad:** 1956 | 1957 | ```javascript 1958 | class InventoryRequester { 1959 | constructor() { 1960 | this.REQ_METHODS = ["HTTP"]; 1961 | } 1962 | 1963 | requestItem(item) { 1964 | // ... 1965 | } 1966 | } 1967 | 1968 | class InventoryTracker { 1969 | constructor(items) { 1970 | this.items = items; 1971 | 1972 | // BAD: We have created a dependency on a specific request implementation. 1973 | // We should just have requestItems depend on a request method: `request` 1974 | this.requester = new InventoryRequester(); 1975 | } 1976 | 1977 | requestItems() { 1978 | this.items.forEach(item => { 1979 | this.requester.requestItem(item); 1980 | }); 1981 | } 1982 | } 1983 | 1984 | const inventoryTracker = new InventoryTracker(["apples", "bananas"]); 1985 | inventoryTracker.requestItems(); 1986 | ``` 1987 | 1988 | **Good:** 1989 | 1990 | ```javascript 1991 | class InventoryTracker { 1992 | constructor(items, requester) { 1993 | this.items = items; 1994 | this.requester = requester; 1995 | } 1996 | 1997 | requestItems() { 1998 | this.items.forEach(item => { 1999 | this.requester.requestItem(item); 2000 | }); 2001 | } 2002 | } 2003 | 2004 | class InventoryRequesterV1 { 2005 | constructor() { 2006 | this.REQ_METHODS = ["HTTP"]; 2007 | } 2008 | 2009 | requestItem(item) { 2010 | // ... 2011 | } 2012 | } 2013 | 2014 | class InventoryRequesterV2 { 2015 | constructor() { 2016 | this.REQ_METHODS = ["WS"]; 2017 | } 2018 | 2019 | requestItem(item) { 2020 | // ... 2021 | } 2022 | } 2023 | 2024 | // By constructing our dependencies externally and injecting them, we can easily 2025 | // substitute our request module for a fancy new one that uses WebSockets. 2026 | const inventoryTracker = new InventoryTracker( 2027 | ["apples", "bananas"], 2028 | new InventoryRequesterV2() 2029 | ); 2030 | inventoryTracker.requestItems(); 2031 | ``` 2032 | 2033 | **[⬆ back to top](#table-of-contents)** 2034 | 2035 | ## **Testing** 2036 | 2037 | Testing is more important than shipping. If you have no tests or an 2038 | inadequate amount, then every time you ship code you won't be sure that you 2039 | didn't break anything. Deciding on what constitutes an adequate amount is up 2040 | to your team, but having 100% coverage (all statements and branches) is how 2041 | you achieve very high confidence and developer peace of mind. This means that 2042 | in addition to having a great testing framework, you also need to use a 2043 | [good coverage tool](https://gotwarlost.github.io/istanbul/). 2044 | 2045 | آزمایش مهمتر از حمل و نقل است. اگر هیچ آزمایشی ندارید یا 2046 | مقدار ناکافی است، پس هر بار که کد ارسال می کنید، مطمئن نخواهید بود که چیزی را شکسته اید. تصمیم گیری در مورد اینکه چه چیزی مقدار کافی را تشکیل می دهد به تیم شما بستگی دارد، اما داشتن پوشش 100٪ (همه اظهارات و شعبه ها) چگونه به اعتماد بسیار بالا و آرامش خاطر توسعه دهنده دست می یابد. این بدان معناست که علاوه بر داشتن یک چارچوب تست عالی، باید از یک ابزار پوشش خوب نیز استفاده کنید 2047 | 2048 | 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. 2049 | When you find one that works for your team, then aim to always write tests 2050 | for every new feature/module you introduce. If your preferred method is 2051 | Test Driven Development (TDD), that is great, but the main point is to just 2052 | make sure you are reaching your coverage goals before launching any feature, 2053 | or refactoring an existing one. 2054 | 2055 | هیچ بهانه ای برای ننوشتن تست وجود ندارد. فریمورک‌های تست JS خوب زیادی وجود دارد، بنابراین یکی را پیدا کنید که تیم شما ترجیح می‌دهد. 2056 | وقتی یکی را پیدا کردید که برای تیم شما کار می کند، پس هدف خود را بنویسید که همیشه برای هر ویژگی/ماژول جدیدی که معرفی می کنید، تست بنویسید. اگر روش ترجیحی شما توسعه تست محور (TDD) است، عالی است، اما نکته اصلی این است که فقط مطمئن شوید که قبل از راه‌اندازی هر ویژگی یا بازسازی یک ویژگی موجود، به اهداف پوشش خود می‌رسید. 2057 | 2058 | ### Single concept per test 2059 | 2060 | ### مفهوم واحد در هر آزمون 2061 | 2062 | **Bad:** 2063 | 2064 | ```javascript 2065 | import assert from "assert"; 2066 | 2067 | describe("MomentJS", () => { 2068 | it("handles date boundaries", () => { 2069 | let date; 2070 | 2071 | date = new MomentJS("1/1/2015"); 2072 | date.addDays(30); 2073 | assert.equal("1/31/2015", date); 2074 | 2075 | date = new MomentJS("2/1/2016"); 2076 | date.addDays(28); 2077 | assert.equal("02/29/2016", date); 2078 | 2079 | date = new MomentJS("2/1/2015"); 2080 | date.addDays(28); 2081 | assert.equal("03/01/2015", date); 2082 | }); 2083 | }); 2084 | ``` 2085 | 2086 | **Good:** 2087 | 2088 | ```javascript 2089 | import assert from "assert"; 2090 | 2091 | describe("MomentJS", () => { 2092 | it("handles 30-day months", () => { 2093 | const date = new MomentJS("1/1/2015"); 2094 | date.addDays(30); 2095 | assert.equal("1/31/2015", date); 2096 | }); 2097 | 2098 | it("handles leap year", () => { 2099 | const date = new MomentJS("2/1/2016"); 2100 | date.addDays(28); 2101 | assert.equal("02/29/2016", date); 2102 | }); 2103 | 2104 | it("handles non-leap year", () => { 2105 | const date = new MomentJS("2/1/2015"); 2106 | date.addDays(28); 2107 | assert.equal("03/01/2015", date); 2108 | }); 2109 | }); 2110 | ``` 2111 | 2112 | **[⬆ back to top](#table-of-contents)** 2113 | 2114 | ## **Concurrency** 2115 | 2116 | ## **همزمان** 2117 | 2118 | ### Use Promises, not callbacks 2119 | 2120 | ### از Promises استفاده کنید نه callback 2121 | 2122 | Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6, 2123 | Promises are a built-in global type. Use them! 2124 | 2125 | کالبک ها تمیز نیستند و باعث ایجاد مقدار زیادی تودرتو می شوند. با ES2015/ES6، Promises یک نوع جهانی داخلی است. از آنها استفاده کنید! 2126 | **Bad:** 2127 | 2128 | ```javascript 2129 | import { get } from "request"; 2130 | import { writeFile } from "fs"; 2131 | 2132 | get( 2133 | "https://en.wikipedia.org/wiki/Robert_Cecil_Martin", 2134 | (requestErr, response, body) => { 2135 | if (requestErr) { 2136 | console.error(requestErr); 2137 | } else { 2138 | writeFile("article.html", body, writeErr => { 2139 | if (writeErr) { 2140 | console.error(writeErr); 2141 | } else { 2142 | console.log("File written"); 2143 | } 2144 | }); 2145 | } 2146 | } 2147 | ); 2148 | ``` 2149 | 2150 | **Good:** 2151 | 2152 | ```javascript 2153 | import { get } from "request-promise"; 2154 | import { writeFile } from "fs-extra"; 2155 | 2156 | get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") 2157 | .then(body => { 2158 | return writeFile("article.html", body); 2159 | }) 2160 | .then(() => { 2161 | console.log("File written"); 2162 | }) 2163 | .catch(err => { 2164 | console.error(err); 2165 | }); 2166 | ``` 2167 | 2168 | **[⬆ back to top](#table-of-contents)** 2169 | 2170 | ### Async/Await are even cleaner than Promises 2171 | 2172 | ### Async/Await حتی تمیزتر از Promises هستند 2173 | 2174 | Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await 2175 | which offer an even cleaner solution. All you need is a function that is prefixed 2176 | in an `async` keyword, and then you can write your logic imperatively without 2177 | a `then` chain of functions. Use this if you can take advantage of ES2017/ES8 features 2178 | today! 2179 | 2180 | Promises جایگزین بسیار تمیزی برای تماس‌های برگشتی است، اما ES2017/ES8 همگام‌سازی و انتظار را به ارمغان می‌آورد که راه‌حلی حتی تمیزتر ارائه می‌دهد. تنها چیزی که نیاز دارید تابعی است که در یک کلمه کلیدی «ناهمگام» پیشوند باشد، و سپس می توانید منطق خود را به طور ضروری بدون زنجیره توابع «آنگاه» بنویسید. اگر امروز می توانید از ویژگی های ES2017/ES8 استفاده کنید، از این استفاده کنید! 2181 | 2182 | **Bad:** 2183 | 2184 | ```javascript 2185 | import { get } from "request-promise"; 2186 | import { writeFile } from "fs-extra"; 2187 | 2188 | get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") 2189 | .then(body => { 2190 | return writeFile("article.html", body); 2191 | }) 2192 | .then(() => { 2193 | console.log("File written"); 2194 | }) 2195 | .catch(err => { 2196 | console.error(err); 2197 | }); 2198 | ``` 2199 | 2200 | **Good:** 2201 | 2202 | ```javascript 2203 | import { get } from "request-promise"; 2204 | import { writeFile } from "fs-extra"; 2205 | 2206 | async function getCleanCodeArticle() { 2207 | try { 2208 | const body = await get( 2209 | "https://en.wikipedia.org/wiki/Robert_Cecil_Martin" 2210 | ); 2211 | await writeFile("article.html", body); 2212 | console.log("File written"); 2213 | } catch (err) { 2214 | console.error(err); 2215 | } 2216 | } 2217 | 2218 | getCleanCodeArticle() 2219 | ``` 2220 | 2221 | **[⬆ back to top](#table-of-contents)** 2222 | 2223 | ## **Error Handling** 2224 | 2225 | ## ** رسیدگی به خطا** 2226 | 2227 | Thrown errors are a good thing! They mean the runtime has successfully 2228 | identified when something in your program has gone wrong and it's letting 2229 | you know by stopping function execution on the current stack, killing the 2230 | process (in Node), and notifying you in the console with a stack trace. 2231 | 2232 | خطاهای پرتاب شده چیز خوبی است! آنها به این معنی هستند که زمان اجرا با موفقیت شناسایی شده است که مشکلی در برنامه شما اشتباه شده است و با متوقف کردن اجرای عملکرد در پشته فعلی، از بین بردن فرآیند (در Node) و اطلاع شما در کنسول با یک stack trace به شما اطلاع می دهد. 2233 | 2234 | ### Don't ignore caught errors 2235 | 2236 | ### خطاهای کشف شده را نادیده نگیرید 2237 | 2238 | Doing nothing with a caught error doesn't give you the ability to ever fix 2239 | or react to said error. Logging the error to the console (`console.log`) 2240 | isn't much better as often times it can get lost in a sea of things printed 2241 | to the console. If you wrap any bit of code in a `try/catch` it means you 2242 | think an error may occur there and therefore you should have a plan, 2243 | or create a code path, for when it occurs. 2244 | 2245 | انجام هیچ کاری با خطای کشف شده به شما این توانایی را نمی دهد که هرگز خطای گفته شده را برطرف کنید یا به آن واکنش نشان دهید. ثبت خطا در کنسول ('console.log') خیلی بهتر نیست زیرا اغلب اوقات ممکن است در دریایی از چیزهایی که روی کنسول چاپ شده گم شود. اگر هر بیت کدی را در یک «try/catch» بپیچید به این معنی است که فکر می‌کنید ممکن است خطایی در آنجا رخ دهد و بنابراین باید برای زمانی که رخ می‌دهد یک برنامه داشته باشید یا یک مسیر کد ایجاد کنید. 2246 | 2247 | **Bad:** 2248 | 2249 | ```javascript 2250 | try { 2251 | functionThatMightThrow(); 2252 | } catch (error) { 2253 | console.log(error); 2254 | } 2255 | ``` 2256 | 2257 | **Good:** 2258 | 2259 | ```javascript 2260 | try { 2261 | functionThatMightThrow(); 2262 | } catch (error) { 2263 | // One option (more noisy than console.log): 2264 | console.error(error); 2265 | // Another option: 2266 | notifyUserOfError(error); 2267 | // Another option: 2268 | reportErrorToService(error); 2269 | // OR do all three! 2270 | } 2271 | ``` 2272 | 2273 | ### Don't ignore rejected promises 2274 | 2275 | For the same reason you shouldn't ignore caught errors 2276 | from `try/catch`. 2277 | 2278 | **Bad:** 2279 | 2280 | ```javascript 2281 | getdata() 2282 | .then(data => { 2283 | functionThatMightThrow(data); 2284 | }) 2285 | .catch(error => { 2286 | console.log(error); 2287 | }); 2288 | ``` 2289 | 2290 | **Good:** 2291 | 2292 | ```javascript 2293 | getdata() 2294 | .then(data => { 2295 | functionThatMightThrow(data); 2296 | }) 2297 | .catch(error => { 2298 | // One option (more noisy than console.log): 2299 | console.error(error); 2300 | // Another option: 2301 | notifyUserOfError(error); 2302 | // Another option: 2303 | reportErrorToService(error); 2304 | // OR do all three! 2305 | }); 2306 | ``` 2307 | 2308 | **[⬆ back to top](#table-of-contents)** 2309 | 2310 | ## **Formatting** 2311 | 2312 | ## **قالب بندی** 2313 | 2314 | Formatting is subjective. Like many rules herein, there is no hard and fast 2315 | rule that you must follow. The main point is DO NOT ARGUE over formatting. 2316 | There are [tons of tools](https://standardjs.com/rules.html) to automate this. 2317 | Use one! It's a waste of time and money for engineers to argue over formatting. 2318 | 2319 | For things that don't fall under the purview of automatic formatting 2320 | (indentation, tabs vs. spaces, double vs. single quotes, etc.) look here 2321 | for some guidance. 2322 | 2323 | قالب بندی ذهنی است. مانند بسیاری از قوانین در اینجا، هیچ قانون سخت و سریعی وجود ندارد که باید از آن پیروی کنید. نکته اصلی این است که بر سر قالب بندی بحث نکنید. هزاران ابزار برای خودکارسازی این کار وجود دارد. از یکی استفاده کن بحث در مورد قالب بندی برای مهندسان اتلاف وقت و پول است. 2324 | برای مواردی که در حیطه قالب بندی خودکار قرار نمی گیرند 2325 | (تورفتگی، برگه ها در مقابل فاصله، دو برابر در مقابل تک نقل قول ها، و غیره) اینجا را ببینید 2326 | برای راهنمایی 2327 | ### Use consistent capitalization 2328 | ### از حروف بزرگ استفاده کنید 2329 | 2330 | JavaScript is untyped, so capitalization tells you a lot about your variables, 2331 | functions, etc. These rules are subjective, so your team can choose whatever 2332 | they want. The point is, no matter what you all choose, just be consistent. 2333 | 2334 | جاوا اسکریپت بدون تایپ است، بنابراین حروف بزرگ به شما چیزهای زیادی در مورد متغیرها، توابع و غیره می گوید. این قوانین ذهنی هستند، بنابراین تیم شما می تواند هر چیزی را که می خواهد انتخاب کند. نکته این است که مهم نیست که همه شما چه چیزی را انتخاب می کنید، فقط ثابت قدم باشید. 2335 | 2336 | **Bad:** 2337 | 2338 | ```javascript 2339 | const DAYS_IN_WEEK = 7; 2340 | const daysInMonth = 30; 2341 | 2342 | const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"]; 2343 | const Artists = ["ACDC", "Led Zeppelin", "The Beatles"]; 2344 | 2345 | function eraseDatabase() {} 2346 | function restore_database() {} 2347 | 2348 | class animal {} 2349 | class Alpaca {} 2350 | ``` 2351 | 2352 | **Good:** 2353 | 2354 | ```javascript 2355 | const DAYS_IN_WEEK = 7; 2356 | const DAYS_IN_MONTH = 30; 2357 | 2358 | const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"]; 2359 | const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"]; 2360 | 2361 | function eraseDatabase() {} 2362 | function restoreDatabase() {} 2363 | 2364 | class Animal {} 2365 | class Alpaca {} 2366 | ``` 2367 | 2368 | **[⬆ back to top](#table-of-contents)** 2369 | 2370 | ### Function callers and callees should be close 2371 | 2372 | ### تماس گیرندگان تابع و تماس گیرندگان باید نزدیک باشند 2373 | 2374 | If a function calls another, keep those functions vertically close in the source 2375 | file. Ideally, keep the caller right above the callee. We tend to read code from 2376 | top-to-bottom, like a newspaper. Because of this, make your code read that way. 2377 | 2378 | اگر تابع دیگری را فراخوانی کرد، آن توابع را به صورت عمودی در فایل منبع نزدیک نگه دارید. در حالت ایده آل، تماس گیرنده را درست بالای تماس گیرنده نگه دارید. ما تمایل داریم مانند یک روزنامه، کد را از بالا به پایین بخوانیم. به همین دلیل، کد خود را به این ترتیب بخوانید. 2379 | 2380 | **Bad:** 2381 | 2382 | ```javascript 2383 | class PerformanceReview { 2384 | constructor(employee) { 2385 | this.employee = employee; 2386 | } 2387 | 2388 | lookupPeers() { 2389 | return db.lookup(this.employee, "peers"); 2390 | } 2391 | 2392 | lookupManager() { 2393 | return db.lookup(this.employee, "manager"); 2394 | } 2395 | 2396 | getPeerReviews() { 2397 | const peers = this.lookupPeers(); 2398 | // ... 2399 | } 2400 | 2401 | perfReview() { 2402 | this.getPeerReviews(); 2403 | this.getManagerReview(); 2404 | this.getSelfReview(); 2405 | } 2406 | 2407 | getManagerReview() { 2408 | const manager = this.lookupManager(); 2409 | } 2410 | 2411 | getSelfReview() { 2412 | // ... 2413 | } 2414 | } 2415 | 2416 | const review = new PerformanceReview(employee); 2417 | review.perfReview(); 2418 | ``` 2419 | 2420 | **Good:** 2421 | 2422 | ```javascript 2423 | class PerformanceReview { 2424 | constructor(employee) { 2425 | this.employee = employee; 2426 | } 2427 | 2428 | perfReview() { 2429 | this.getPeerReviews(); 2430 | this.getManagerReview(); 2431 | this.getSelfReview(); 2432 | } 2433 | 2434 | getPeerReviews() { 2435 | const peers = this.lookupPeers(); 2436 | // ... 2437 | } 2438 | 2439 | lookupPeers() { 2440 | return db.lookup(this.employee, "peers"); 2441 | } 2442 | 2443 | getManagerReview() { 2444 | const manager = this.lookupManager(); 2445 | } 2446 | 2447 | lookupManager() { 2448 | return db.lookup(this.employee, "manager"); 2449 | } 2450 | 2451 | getSelfReview() { 2452 | // ... 2453 | } 2454 | } 2455 | 2456 | const review = new PerformanceReview(employee); 2457 | review.perfReview(); 2458 | ``` 2459 | 2460 | **[⬆ back to top](#table-of-contents)** 2461 | 2462 | ## **Comments** 2463 | 2464 | ## **کامنتها** 2465 | 2466 | ### Only comment things that have business logic complexity. 2467 | ### فقط چیزهایی را که دارای پیچیدگی منطق تجاری هستند کامنت دهید. 2468 | 2469 | Comments are an apology, not a requirement. Good code _mostly_ documents itself. 2470 | 2471 | کامنتها یک عذرخواهی است نه یک الزام. کد خوب _بیشتر_ خود سندی است برای خود. 2472 | **Bad:** 2473 | 2474 | ```javascript 2475 | function hashIt(data) { 2476 | // The hash 2477 | let hash = 0; 2478 | 2479 | // Length of string 2480 | const length = data.length; 2481 | 2482 | // Loop through every character in data 2483 | for (let i = 0; i < length; i++) { 2484 | // Get character code. 2485 | const char = data.charCodeAt(i); 2486 | // Make the hash 2487 | hash = (hash << 5) - hash + char; 2488 | // Convert to 32-bit integer 2489 | hash &= hash; 2490 | } 2491 | } 2492 | ``` 2493 | 2494 | **Good:** 2495 | 2496 | ```javascript 2497 | function hashIt(data) { 2498 | let hash = 0; 2499 | const length = data.length; 2500 | 2501 | for (let i = 0; i < length; i++) { 2502 | const char = data.charCodeAt(i); 2503 | hash = (hash << 5) - hash + char; 2504 | 2505 | // Convert to 32-bit integer 2506 | hash &= hash; 2507 | } 2508 | } 2509 | ``` 2510 | 2511 | **[⬆ back to top](#table-of-contents)** 2512 | 2513 | ### Don't leave commented out code in your codebase 2514 | 2515 | ### کد کامنت شده را در پایگاه کد خود نگذارید 2516 | 2517 | Version control exists for a reason. Leave old code in your history. 2518 | 2519 | کنترل نسخه به دلایلی وجود دارد. کدهای قدیمی را در تاریخچه خود بگذارید. 2520 | 2521 | **Bad:** 2522 | 2523 | ```javascript 2524 | doStuff(); 2525 | // doOtherStuff(); 2526 | // doSomeMoreStuff(); 2527 | // doSoMuchStuff(); 2528 | ``` 2529 | 2530 | **Good:** 2531 | 2532 | ```javascript 2533 | doStuff(); 2534 | ``` 2535 | 2536 | **[⬆ back to top](#table-of-contents)** 2537 | 2538 | ### Don't have journal comments 2539 | 2540 | Remember, use version control! There's no need for dead code, commented code, 2541 | and especially journal comments. Use `git log` to get history! 2542 | 2543 | **Bad:** 2544 | 2545 | ```javascript 2546 | /** 2547 | * 2016-12-20: Removed monads, didn't understand them (RM) 2548 | * 2016-10-01: Improved using special monads (JP) 2549 | * 2016-02-03: Removed type-checking (LI) 2550 | * 2015-03-14: Added combine with type-checking (JR) 2551 | */ 2552 | function combine(a, b) { 2553 | return a + b; 2554 | } 2555 | ``` 2556 | 2557 | **Good:** 2558 | 2559 | ```javascript 2560 | function combine(a, b) { 2561 | return a + b; 2562 | } 2563 | ``` 2564 | 2565 | **[⬆ back to top](#table-of-contents)** 2566 | 2567 | ### Avoid positional markers 2568 | 2569 | ### از نشانگرهای موقعیتی خودداری کنید 2570 | 2571 | They usually just add noise. Let the functions and variable names along with the 2572 | proper indentation and formatting give the visual structure to your code. 2573 | 2574 | آنها معمولا فقط نویز اضافه می کنند. اجازه دهید توابع و نام متغیرها به همراه تورفتگی و قالب بندی مناسب ساختار بصری کد شما را ایجاد کنند. 2575 | 2576 | **Bad:** 2577 | 2578 | ```javascript 2579 | //////////////////////////////////////////////////////////////////////////////// 2580 | // Scope Model Instantiation 2581 | //////////////////////////////////////////////////////////////////////////////// 2582 | $scope.model = { 2583 | menu: "foo", 2584 | nav: "bar" 2585 | }; 2586 | 2587 | //////////////////////////////////////////////////////////////////////////////// 2588 | // Action setup 2589 | //////////////////////////////////////////////////////////////////////////////// 2590 | const actions = function() { 2591 | // ... 2592 | }; 2593 | ``` 2594 | 2595 | **Good:** 2596 | 2597 | ```javascript 2598 | $scope.model = { 2599 | menu: "foo", 2600 | nav: "bar" 2601 | }; 2602 | 2603 | const actions = function() { 2604 | // ... 2605 | }; 2606 | ``` 2607 | 2608 | **[⬆ back to top](#table-of-contents)** 2609 | 2610 | ## Translation 2611 | 2612 | This is also available in other languages: 2613 | 2614 | - ![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) 2615 | - ![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/) 2616 | - ![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) 2617 | - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Simplified Chinese**: 2618 | - [alivebao/clean-code-js](https://github.com/alivebao/clean-code-js) 2619 | - [beginor/clean-code-javascript](https://github.com/beginor/clean-code-javascript) 2620 | - ![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) 2621 | - ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [GavBaros/clean-code-javascript-fr](https://github.com/GavBaros/clean-code-javascript-fr) 2622 | - ![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) 2623 | - ![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/) 2624 | - ![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/) 2625 | - ![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/) 2626 | - ![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) 2627 | - ![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) 2628 | - ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: 2629 | - [BoryaMogila/clean-code-javascript-ru/](https://github.com/BoryaMogila/clean-code-javascript-ru/) 2630 | - [maksugr/clean-code-javascript](https://github.com/maksugr/clean-code-javascript) 2631 | - ![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) 2632 | - ![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) 2633 | - ![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) 2634 | - ![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) 2635 | - ![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) 2636 | - ![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/) 2637 | 2638 | **[⬆ back to top](#table-of-contents)** 2639 | --------------------------------------------------------------------------------