diff --git a/README.md b/README.md index 78d5d33..896175c 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,44 @@ # clean-code-typescript [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Clean%20Code%20Typescript&url=https://github.com/labs42io/clean-code-typescript) -Clean Code concepts adapted for TypeScript. -Inspired from [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript). +Концепції Clean Code, адаптовані для TypeScript. +Натхненні [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript). -## Table of Contents +## Зміст - 1. [Introduction](#introduction) - 2. [Variables](#variables) - 3. [Functions](#functions) - 4. [Objects and Data Structures](#objects-and-data-structures) - 5. [Classes](#classes) + 1. [Вступ](#вступ) + 2. [Змінні](#змінні) + 3. [Функції](#функції) + 4. [Об'єкти та структури даних](#обєкти-та-структури-даних) + 5. [Класи](#класи) 6. [SOLID](#solid) - 7. [Testing](#testing) - 8. [Concurrency](#concurrency) - 9. [Error Handling](#error-handling) - 10. [Formatting](#formatting) - 11. [Comments](#comments) - 12. [Translations](#translations) + 7. [Тестування](#тестування) + 8. [Паралельність](#паралельність) + 9. [Обробка помилок](#обробка-помилок) + 10. [Форматування](#форматування) + 11. [Коментарі](#коментарі) + 12. [Переклади](#переклади) -## Introduction +## Вступ -![Humorous image of software quality estimation as a count of how many expletives -you shout when reading code](https://www.osnews.com/images/comics/wtfm.jpg) +![Гумористичне зображення оцінки якості програмного забезпечення як кількості лайливих слів, які ви вигукуєте, коли читаєте код](https://www.osnews.com/images/comics/wtfm.jpg) -Software engineering principles, from Robert C. Martin's book -[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), -adapted for TypeScript. This is not a style guide. It's a guide to producing -[readable, reusable, and refactorable](https://github.com/ryanmcdermott/3rs-of-software-architecture) software in TypeScript. +Принципи програмної інженерії з книги Роберта К. Мартіна [*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), адаптовані для TypeScript. Це не стильовий посібник. Це посібник з написання [читабельного, повторно використовуваного та рефакторингового](https://github.com/ryanmcdermott/3rs-of-software-architecture) програмного забезпечення на TypeScript. -Not every principle herein has to be strictly followed, and even fewer will be -universally agreed upon. These are guidelines and nothing more, but they are -ones codified over many years of collective experience by the authors of -*Clean Code*. +Не кожен принцип тут повинен суворо дотримуватись, і ще менше з них будуть загальноприйнятими. Це лише рекомендації, і нічого більше, але вони кодифіковані багаторічним колективним досвідом авторів книги *Clean Code*. -Our craft of software engineering is just a bit over 50 years old, and we are -still learning a lot. When software architecture is as old as architecture -itself, maybe then we will have harder rules to follow. For now, let these -guidelines serve as a touchstone by which to assess the quality of the -TypeScript code that you and your team produce. +Наше ремесло програмної інженерії налічує лише трохи більше 50 років, і ми все ще багато чого вчимося. Коли архітектура програмного забезпечення стане такою ж старою, як архітектура будівель, можливо, тоді у нас будуть жорсткіші правила для дотримання. А поки що, нехай ці рекомендації слугують орієнтиром для оцінки якості коду TypeScript, який створюєте ви та ваша команда. -One more thing: knowing these won't immediately make you a better software -developer, and working with them for many years doesn't mean you won't make -mistakes. Every piece of code starts as a first draft, like wet clay getting -shaped into its final form. Finally, we chisel away the imperfections when -we review it with our peers. Don't beat yourself up for first drafts that need -improvement. Beat up the code instead! +Ще одна річ: знання цих принципів не зробить вас миттєво кращим розробником програмного забезпечення, і робота з ними протягом багатьох років не означає, що ви не будете помилятися. Кожен фрагмент коду починається як перший чернетковий варіант, як мокра глина, що набуває своєї остаточної форми. Врешті-решт, ми вирізаємо недоліки, коли переглядаємо код з колегами. Не картайте себе за перші чернетки, які потребують покращення. Натомість критикуйте сам код! -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -## Variables +## Змінні -### Use meaningful variable names +### Використовуйте змістовні імена змінних -Distinguish names in such a way that the reader knows what the differences offer. +Розрізняйте імена таким чином, щоб читач розумів, які між ними відмінності. -**Bad:** +**Погано:** ```ts function between(a1: T, a2: T, a3: T): boolean { @@ -63,7 +47,7 @@ function between(a1: T, a2: T, a3: T): boolean { ``` -**Good:** +**Добре:** ```ts function between(value: T, left: T, right: T): boolean { @@ -71,13 +55,13 @@ function between(value: T, left: T, right: T): boolean { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use pronounceable variable names +### Використовуйте вимовні імена змінних -If you can’t pronounce it, you can’t discuss it without sounding like an idiot. +Якщо ви не можете вимовити ім'я змінної, ви не зможете обговорювати її, не звучачи як ідіот. -**Bad:** +**Погано:** ```ts type DtaRcrd102 = { @@ -87,7 +71,7 @@ type DtaRcrd102 = { } ``` -**Good:** +**Добре:** ```ts type Customer = { @@ -97,11 +81,11 @@ type Customer = { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use the same vocabulary for the same type of variable +### Використовуйте однаковий словниковий запас для однакового типу змінних -**Bad:** +**Погано:** ```ts function getUserInfo(): User; @@ -109,66 +93,66 @@ function getUserDetails(): User; function getUserData(): User; ``` -**Good:** +**Добре:** ```ts function getUser(): User; ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use searchable names +### Використовуйте пошукові імена -We will read more code than we will ever write. It's important that the code we do write must be readable and searchable. By *not* naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools like [ESLint](https://typescript-eslint.io/) can help identify unnamed constants (also known as magic strings and magic numbers). +Ми будемо читати більше коду, ніж коли-небудь напишемо. Важливо, щоб код, який ми пишемо, був читабельним і пошуковим. Не називаючи змінні іменами, які мають значення для розуміння нашої програми, ми шкодимо нашим читачам. Робіть ваші імена пошуковими. Інструменти, такі як [ESLint](https://typescript-eslint.io/), можуть допомогти ідентифікувати неназвані константи (також відомі як магічні рядки та магічні числа). -**Bad:** +**Погано:** ```ts -// What the heck is 86400000 for? +// Що за чорт, для чого ці 86400000? setTimeout(restart, 86400000); ``` -**Good:** +**Добре:** ```ts -// Declare them as capitalized named constants. +// Оголосіть їх як капіталізовані іменовані константи. const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; // 86400000 setTimeout(restart, MILLISECONDS_PER_DAY); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use explanatory variables +### Використовуйте пояснювальні змінні -**Bad:** +**Погано:** ```ts declare const users: Map; for (const keyValue of users) { - // iterate through users map + // ітерація по мапі користувачів } ``` -**Good:** +**Добре:** ```ts declare const users: Map; for (const [id, user] of users) { - // iterate through users map + // ітерація по мапі користувачів } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Avoid Mental Mapping +### Уникайте ментального картування -Explicit is better than implicit. -*Clarity is king.* +Явне краще, ніж неявне. +*Чіткість - це король.* -**Bad:** +**Погано:** ```ts const u = getUser(); @@ -176,7 +160,7 @@ const s = getSubscription(); const t = charge(u, s); ``` -**Good:** +**Добре:** ```ts const user = getUser(); @@ -184,13 +168,13 @@ const subscription = getSubscription(); const transaction = charge(user, subscription); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Don't add unneeded context +### Не додавайте непотрібний контекст -If your class/type/object name tells you something, don't repeat that in your variable name. +Якщо ім'я вашого класу/типу/об'єкта говорить вам щось, не повторюйте це в імені змінної. -**Bad:** +**Погано:** ```ts type Car = { @@ -204,7 +188,7 @@ function print(car: Car): void { } ``` -**Good:** +**Добре:** ```ts type Car = { @@ -218,13 +202,13 @@ function print(car: Car): void { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use default arguments instead of short circuiting or conditionals +### Використовуйте аргументи за замовчуванням замість короткого зациклення або умов -Default arguments are often cleaner than short circuiting. +Аргументи за замовчуванням часто чистіші, ніж коротке зациклення. -**Bad:** +**Погано:** ```ts function loadPages(count?: number) { @@ -233,7 +217,7 @@ function loadPages(count?: number) { } ``` -**Good:** +**Добре:** ```ts function loadPages(count: number = 10) { @@ -241,14 +225,13 @@ function loadPages(count: number = 10) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Use enum to document the intent +### Використовуйте enum для документування наміру -Enums can help you document the intent of the code. For example when we are concerned about values being -different rather than the exact value of those. +Перерахування (enums) можуть допомогти вам документувати намір коду. Наприклад, коли ми більше турбуємося про те, щоб значення відрізнялись, ніж про їх точне значення. -**Bad:** +**Погано:** ```ts const GENRE = { @@ -261,17 +244,17 @@ const GENRE = { projector.configureFilm(GENRE.COMEDY); class Projector { - // declaration of Projector + // декларація Projector configureFilm(genre) { switch (genre) { case GENRE.ROMANTIC: - // some logic to be executed + // якась логіка для виконання } } } ``` -**Good:** +**Добре:** ```ts enum GENRE { @@ -284,43 +267,43 @@ enum GENRE { projector.configureFilm(GENRE.COMEDY); class Projector { - // declaration of Projector + // декларація Projector configureFilm(genre) { switch (genre) { case GENRE.ROMANTIC: - // some logic to be executed + // якась логіка для виконання } } } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -## Functions +## Функції -### Function arguments (2 or fewer ideally) +### Аргументи функцій (в ідеалі 2 або менше) -Limiting the number of function parameters is incredibly important because it makes testing your function easier. -Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument. +Обмеження кількості параметрів функції неймовірно важливе, оскільки це полегшує тестування вашої функції. +Наявність більше трьох призводить до комбінаторного вибуху, коли ви повинні тестувати тонни різних випадків для кожного окремого аргументу. -One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated. -Usually, if you have more than two arguments then your function is trying to do too much. -In cases where it's not, most of the time a higher-level object will suffice as an argument. +Один або два аргументи - це ідеальний випадок, а трьох слід уникати, якщо це можливо. Все, що перевищує це, має бути консолідовано. +Зазвичай, якщо у вас більше двох аргументів, то ваша функція намагається зробити занадто багато. +У випадках, коли це не так, здебільшого об'єкт вищого рівня буде достатнім як аргумент. -Consider using object literals if you are finding yourself needing a lot of arguments. +Розгляньте можливість використання об'єктних літералів, якщо вам потрібно багато аргументів. -To make it obvious what properties the function expects, you can use the [destructuring](https://basarat.gitbook.io/typescript/future-javascript/destructuring) syntax. -This has a few advantages: +Щоб було очевидно, які властивості очікує функція, ви можете використовувати синтаксис [деструктуризації](https://basarat.gitbook.io/typescript/future-javascript/destructuring). +Це має кілька переваг: -1. When someone looks at the function signature, it's immediately clear what properties are being used. +1. Коли хтось дивиться на сигнатуру функції, відразу зрозуміло, які властивості використовуються. -2. It can be used to simulate named parameters. +2. Це можна використовувати для імітації іменованих параметрів. -3. Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned. +3. Деструктуризація також клонує вказані примітивні значення об'єкта аргументу, переданого у функцію. Це може допомогти запобігти побічним ефектам. Примітка: об'єкти та масиви, які деструктуризуються з об'єкта аргументу, НЕ клонуються. -4. TypeScript warns you about unused properties, which would be impossible without destructuring. +4. TypeScript попереджає про невикористані властивості, що було б неможливо без деструктуризації. -**Bad:** +**Погано:** ```ts function createMenu(title: string, body: string, buttonText: string, cancellable: boolean) { @@ -330,7 +313,7 @@ function createMenu(title: string, body: string, buttonText: string, cancellable createMenu('Foo', 'Bar', 'Baz', true); ``` -**Good:** +**Добре:** ```ts function createMenu(options: { title: string, body: string, buttonText: string, cancellable: boolean }) { @@ -345,7 +328,7 @@ createMenu({ }); ``` -You can further improve readability by using [type aliases](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases): +Ви можете ще більше покращити читабельність, використовуючи [аліаси типів](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases): ```ts @@ -363,13 +346,13 @@ createMenu({ }); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Functions should do one thing +### Функції повинні робити одне -This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers. +Це, безумовно, найважливіше правило в програмній інженерії. Коли функції роблять більше, ніж одне, їх важче створювати, тестувати та розуміти. Коли ви можете ізолювати функцію до однієї дії, її легко рефакторити, і ваш код буде набагато чистішим. Якщо ви не винесете з цього посібника нічого іншого, крім цього, ви випередите багатьох розробників. -**Bad:** +**Погано:** ```ts function emailActiveClients(clients: Client[]) { @@ -382,7 +365,7 @@ function emailActiveClients(clients: Client[]) { } ``` -**Good:** +**Добре:** ```ts function emailActiveClients(clients: Client[]) { @@ -395,11 +378,11 @@ function isActiveClient(client: Client) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Function names should say what they do +### Назви функцій повинні говорити, що вони роблять -**Bad:** +**Погано:** ```ts function addToDate(date: Date, month: number): Date { @@ -408,11 +391,11 @@ function addToDate(date: Date, month: number): Date { const date = new Date(); -// It's hard to tell from the function name what is added +// Важко зрозуміти з назви функції, що саме додається addToDate(date, 1); ``` -**Good:** +**Добре:** ```ts function addMonthToDate(date: Date, month: number): Date { @@ -423,13 +406,13 @@ const date = new Date(); addMonthToDate(date, 1); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Functions should only be one level of abstraction +### Функції повинні бути лише на одному рівні абстракції -When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing. +Коли у вас більше одного рівня абстракції, ваша функція зазвичай робить занадто багато. Розділення функцій призводить до повторного використання та полегшує тестування. -**Bad:** +**Погано:** ```ts function parseCode(code: string) { @@ -445,16 +428,16 @@ function parseCode(code: string) { const ast = []; tokens.forEach((token) => { - // lex... + // лексичний аналіз... }); ast.forEach((node) => { - // parse... + // парсинг... }); } ``` -**Good:** +**Добре:** ```ts const REGEXES = [ /* ... */ ]; @@ -464,7 +447,7 @@ function parseCode(code: string) { const syntaxTree = parse(tokens); syntaxTree.forEach((node) => { - // parse... + // парсинг... }); } @@ -491,22 +474,22 @@ function parse(tokens: Token[]): SyntaxTree { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Remove duplicate code +### Видаліть дубльований код -Do your absolute best to avoid duplicate code. -Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic. +Зробіть все можливе, щоб уникнути дубльованого коду. +Дубльований код поганий, тому що це означає, що існує більше одного місця для зміни чогось, якщо вам потрібно змінити якусь логіку. -Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. -If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. -If you only have one list, there's only one place to update! +Уявіть, якщо ви керуєте рестораном і ведете облік вашого інвентарю: всіх ваших помідорів, цибулі, часнику, спецій тощо. +Якщо у вас є кілька списків, де ви це зберігаєте, то всі вони повинні бути оновлені, коли ви подаєте страву з помідорами. +Якщо у вас лише один список, є лише одне місце для оновлення! -Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class. +Часто ви маєте дубльований код, тому що у вас є дві або більше дещо різних речей, які мають багато спільного, але їхні відмінності змушують вас мати дві або більше окремі функції, які роблять багато однакових речей. Видалення дубльованого коду означає створення абстракції, яка може обробляти цей набір різних речей лише однією функцією/модулем/класом. -Getting the abstraction right is critical, that's why you should follow the [SOLID](#solid) principles. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise, you'll find yourself updating multiple places anytime you want to change one thing. +Правильна абстракція є критичною, саме тому ви повинні дотримуватися принципів [SOLID](#solid). Погані абстракції можуть бути гіршими за дубльований код, тому будьте обережні! Але якщо ви можете зробити хорошу абстракцію, зробіть це! Не повторюйтеся, інакше ви будете оновлювати кілька місць щоразу, коли захочете змінити одну річ. -**Bad:** +**Погано:** ```ts function showDeveloperList(developers: Developer[]) { @@ -542,7 +525,7 @@ function showManagerList(managers: Manager[]) { } ``` -**Good:** +**Добре:** ```ts class Developer { @@ -580,7 +563,7 @@ function showEmployeeList(employee: (Developer | Manager)[]) { } ``` -You may also consider adding a union type, or common parent class if it suits your abstraction. +Ви також можете розглянути додавання типу об'єднання або спільного батьківського класу, якщо це відповідає вашій абстракції. ```ts class Developer { // ... @@ -599,13 +582,13 @@ function showEmployeeList(employee: Employee[]) { ``` -You should be critical about code duplication. Sometimes there is a tradeoff between duplicated code and increased complexity by introducing unnecessary abstraction. When two implementations from two different modules look similar but live in different domains, duplication might be acceptable and preferred over extracting the common code. The extracted common code, in this case, introduces an indirect dependency between the two modules. +Ви повинні критично ставитися до дублювання коду. Іноді існує компроміс між дубльованим кодом і збільшенням складності через введення непотрібної абстракції. Коли дві реалізації з двох різних модулів виглядають схожими, але живуть у різних доменах, дублювання може бути прийнятним і переважати над витяганням спільного коду. Витягнутий спільний код у цьому випадку створює непряму залежність між двома модулями. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#зміст)** -### Set default objects with Object.assign or destructuring +### Встановлюйте об'єкти за замовчуванням за допомогою Object.assign або деструктуризації -**Bad:** +**Погано:** ```ts type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; @@ -622,7 +605,7 @@ function createMenu(config: MenuConfig) { createMenu({ body: 'Bar' }); ``` -**Good:** +**Добре:** ```ts type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; @@ -641,7 +624,7 @@ function createMenu(config: MenuConfig) { createMenu({ body: 'Bar' }); ``` -Or, you could use the spread operator: +Або ви можете використовувати оператор поширення (spread operator): ```ts function createMenu(config: MenuConfig) { @@ -656,10 +639,10 @@ function createMenu(config: MenuConfig) { // ... } ``` -The spread operator and `Object.assign()` are very similar. -The main difference is that spreading defines new properties, while `Object.assign()` sets them. More detailed, the difference is explained in [this](https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign) thread. +Оператор поширення і `Object.assign()` дуже схожі. +Головна відмінність полягає в тому, що поширення визначає нові властивості, тоді як `Object.assign()` встановлює їх. Більш детально ця різниця пояснюється в [цій](https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign) темі. -Alternatively, you can use destructuring with default values: +Альтернативно, ви можете використовувати деструктуризацію з значеннями за замовчуванням: ```ts type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; @@ -671,17 +654,17 @@ function createMenu({ title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellab createMenu({ body: 'Bar' }); ``` -To avoid any side effects and unexpected behavior by passing in explicitly the `undefined` or `null` value, you can tell the TypeScript compiler to not allow it. -See [`--strictNullChecks`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#--strictnullchecks) option in TypeScript. +Щоб уникнути будь-яких побічних ефектів і неочікуваної поведінки передаючи явно значення `undefined` або `null`, ви можете вказати компілятору TypeScript не дозволяти це. +Дивіться опцію [`--strictNullChecks`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#--strictnullchecks) в TypeScript. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't use flags as function parameters +### Не використовуйте прапорці як параметри функцій -Flags tell your user that this function does more than one thing. -Functions should do one thing. Split out your functions if they are following different code paths based on a boolean. +Прапорці повідомляють вашому користувачеві, що ця функція робить більше однієї речі. +Функції повинні робити одну річ. Розділіть ваші функції, якщо вони слідують різним шляхам коду на основі булевого значення. -**Bad:** +**Погано:** ```ts function createFile(name: string, temp: boolean) { @@ -693,7 +676,7 @@ function createFile(name: string, temp: boolean) { } ``` -**Good:** +**Добре:** ```ts function createTempFile(name: string) { @@ -705,23 +688,23 @@ function createFile(name: string) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid Side Effects (part 1) +### Уникайте побічних ефектів (частина 1) -A function produces a side effect if it does anything other than take a value in and return another value or values. -A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger. +Функція створює побічний ефект, якщо вона робить щось інше, ніж приймає значення і повертає інше значення або значення. +Побічним ефектом може бути запис у файл, зміна глобальної змінної або випадкове перерахування всіх ваших грошей незнайомцю. -Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file. -What you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file. -Have one service that does it. One and only one. +Час від часу вам дійсно потрібні побічні ефекти в програмі. Як у попередньому прикладі, вам може знадобитися запис у файл. +Але те, що ви хочете зробити, це централізувати місце, де ви це робите. Не майте кілька функцій і класів, які записують у певний файл. +Майте одну службу, яка це робить. Одну і тільки одну. -The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers. +Основна ідея полягає в тому, щоб уникнути поширених пасток, таких як обмін станом між об'єктами без структури, використання мутабельних типів даних, які можуть бути змінені будь-чим, і не централізація того, де відбуваються ваші побічні ефекти. Якщо ви зможете це зробити, ви будете щасливіші, ніж більшість інших програмістів. -**Bad:** +**Погано:** ```ts -// Global variable referenced by following function. +// Глобальна змінна, на яку посилається наступна функція. let name = 'Robert C. Martin'; function toBase64() { @@ -729,12 +712,12 @@ function toBase64() { } toBase64(); -// If we had another function that used this name, now it'd be a Base64 value +// Якби у нас була інша функція, яка використовувала це ім'я, тепер це було б значення в Base64 -console.log(name); // expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg==' +console.log(name); // очікується, що надрукує 'Robert C. Martin', але натомість 'Um9iZXJ0IEMuIE1hcnRpbg==' ``` -**Good:** +**Добре:** ```ts const name = 'Robert C. Martin'; @@ -747,25 +730,25 @@ const encodedName = toBase64(name); console.log(name); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid Side Effects (part 2) +### Уникайте побічних ефектів (частина 2) -Browsers and Node.js process only JavaScript, therefore any TypeScript code has to be compiled before running or debugging. In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere. +Браузери та Node.js обробляють лише JavaScript, тому будь-який код TypeScript має бути скомпільований перед запуском або налагодженням. У JavaScript деякі значення незмінні (immutable), а деякі змінні (mutable). Об'єкти та масиви є двома видами мутабельних значень, тому важливо обережно обробляти їх, коли вони передаються як параметри до функції. Функція JavaScript може змінювати властивості об'єкта або змінювати вміст масиву, що може легко спричинити помилки в інших місцях. -Suppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same `cart` array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation: +Припустимо, існує функція, яка приймає параметр масиву, що представляє кошик покупок. Якщо функція вносить зміни в цей масив кошика - наприклад, додаючи товар для покупки - тоді будь-яка інша функція, яка використовує той самий масив `cart`, буде порушена цим додаванням. Це може бути чудово, але також може бути погано. Давайте уявимо погану ситуацію: -The user clicks the "Purchase" button which calls a `purchase` function that spawns a network request and sends the `cart` array to the server. Because of a bad network connection, the `purchase` function has to keep retrying the request. Now, what if in the meantime the user accidentally clicks an "Add to Cart" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because the `cart` array was modified. +Користувач натискає кнопку "Придбати", яка викликає функцію `purchase`, що створює мережевий запит і надсилає масив `cart` на сервер. Через погане мережеве з'єднання функція `purchase` повинна повторювати запит. А що, якщо тим часом користувач випадково натисне кнопку "Додати до кошика" на товарі, який насправді не хоче, перш ніж розпочнеться мережевий запит? Якщо це станеться і мережевий запит розпочнеться, функція покупки надішле випадково доданий товар, оскільки масив `cart` був змінений. -A great solution would be for the `addItemToCart` function to always clone the `cart`, edit it, and return the clone. This would ensure that functions that are still using the old shopping cart wouldn't be affected by the changes. +Відмінним рішенням було б для функції `addItemToCart` завжди клонувати `cart`, редагувати його і повертати клон. Це забезпечило б, що функції, які все ще використовують старий кошик покупок, не будуть порушені змінами. -Two caveats to mention to this approach: +Два застереження щодо цього підходу: -1. There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects! (see [pure function](https://en.wikipedia.org/wiki/Pure_function)) +1. Можуть бути випадки, коли ви дійсно хочете змінити вхідний об'єкт, але коли ви приймаєте цю практику програмування, ви виявите, що такі випадки досить рідкісні. Більшість речей можна переробити так, щоб не було побічних ефектів! (див. [чиста функція](https://en.wikipedia.org/wiki/Pure_function)) -2. Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are [great libraries](https://github.com/immutable-js/immutable-js) that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays. +2. Клонування великих об'єктів може бути дуже дорогим з точки зору продуктивності. На щастя, це не є великою проблемою на практиці, оскільки існують [чудові бібліотеки](https://github.com/immutable-js/immutable-js), які дозволяють такий підхід до програмування бути швидким і не таким інтенсивним щодо пам'яті, як це було б для вас вручну клонувати об'єкти та масиви. -**Bad:** +**Погано:** ```ts function addItemToCart(cart: CartItem[], item: Item): void { @@ -773,7 +756,7 @@ function addItemToCart(cart: CartItem[], item: Item): void { }; ``` -**Good:** +**Добре:** ```ts function addItemToCart(cart: CartItem[], item: Item): CartItem[] { @@ -781,13 +764,13 @@ function addItemToCart(cart: CartItem[], item: Item): CartItem[] { }; ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't write to global functions +### Не пишіть до глобальних функцій -Polluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to extend JavaScript's native Array method to have a `diff` method that could show the difference between two arrays? You could write your new function to the `Array.prototype`, but it could clash with another library that tried to do the same thing. What if that other library was just using `diff` to find the difference between the first and last elements of an array? This is why it would be much better to just use classes and simply extend the `Array` global. +Забруднення глобальних змінних є поганою практикою в JavaScript, оскільки ви можете зіткнутися з іншою бібліотекою, і користувач вашого API не буде про це знати, поки не отримає виняток у продакшені. Давайте подумаємо про приклад: що, якщо ви хочете розширити нативний метод масиву JavaScript, щоб мати метод `diff`, який міг би показати різницю між двома масивами? Ви могли б написати свою нову функцію до `Array.prototype`, але вона могла б зіткнутися з іншою бібліотекою, яка намагалася зробити те саме. Що, якщо ця інша бібліотека використовувала `diff` лише для пошуку різниці між першим і останнім елементами масиву? Ось чому було б набагато краще просто використовувати класи і просто розширювати глобальний `Array`. -**Bad:** +**Погано:** ```ts declare global { @@ -804,7 +787,7 @@ if (!Array.prototype.diff) { } ``` -**Good:** +**Добре:** ```ts class MyArray extends Array { @@ -815,13 +798,13 @@ class MyArray extends Array { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Favor functional programming over imperative programming +### Віддавайте перевагу функціональному програмуванню над імперативним -Favor this style of programming when you can. +Віддавайте перевагу цьому стилю програмування, коли можете. -**Bad:** +**Погано:** ```ts const contributions = [ @@ -847,7 +830,7 @@ for (let i = 0; i < contributions.length; i++) { } ``` -**Good:** +**Добре:** ```ts const contributions = [ @@ -870,11 +853,11 @@ const totalOutput = contributions .reduce((totalLines, output) => totalLines + output.linesOfCode, 0); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Encapsulate conditionals +### Інкапсулюйте умови -**Bad:** +**Погано:** ```ts if (subscription.isTrial || account.balance > 0) { @@ -882,7 +865,7 @@ if (subscription.isTrial || account.balance > 0) { } ``` -**Good:** +**Добре:** ```ts function canActivateService(subscription: Subscription, account: Account) { @@ -894,11 +877,11 @@ if (canActivateService(subscription, account)) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid negative conditionals +### Уникайте негативних умов -**Bad:** +**Погано:** ```ts function isEmailNotUsed(email: string): boolean { @@ -910,7 +893,7 @@ if (isEmailNotUsed(email)) { } ``` -**Good:** +**Добре:** ```ts function isEmailUsed(email: string): boolean { @@ -922,13 +905,13 @@ if (!isEmailUsed(email)) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid conditionals +### Уникайте умов -This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without an `if` statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, "well that's great but why would I want to do that?" The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have `if` statements, you are telling your user that your function does more than one thing. Remember, just do one thing. +Це здається неможливим завданням. При першому почутті цього більшість людей каже: "Як я повинен щось робити без оператора `if`?" Відповідь полягає в тому, що ви можете використовувати поліморфізм для досягнення тієї ж задачі в багатьох випадках. Друге питання зазвичай: "Ну, це чудово, але чому я повинен це робити?" Відповідь - це попередня концепція чистого коду, яку ми вивчили: функція повинна робити тільки одну річ. Коли у вас є класи та функції, які мають оператори `if`, ви повідомляєте своєму користувачеві, що ваша функція робить більше однієї речі. Пам'ятайте, робіть лише одну річ. -**Bad:** +**Погано:** ```ts class Airplane { @@ -954,12 +937,12 @@ class Airplane { } ``` -**Good:** +**Добре:** ```ts abstract class Airplane { protected getMaxAltitude(): number { - // shared logic with subclasses ... + // спільна логіка з підкласами ... } // ... @@ -987,15 +970,15 @@ class Cessna extends Airplane { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid type checking +### Уникайте перевірки типів -TypeScript is a strict syntactical superset of JavaScript and adds optional static type checking to the language. -Always prefer to specify types of variables, parameters and return values to leverage the full power of TypeScript features. -It makes refactoring more easier. +TypeScript є строгим синтаксичним розширенням JavaScript і додає необов'язкову статичну перевірку типів до мови. +Завжди віддавайте перевагу вказанню типів змінних, параметрів і значень, що повертаються, щоб використовувати повну силу можливостей TypeScript. +Це робить рефакторинг легшим. -**Bad:** +**Погано:** ```ts function travelToTexas(vehicle: Bicycle | Car) { @@ -1007,7 +990,7 @@ function travelToTexas(vehicle: Bicycle | Car) { } ``` -**Good:** +**Добре:** ```ts type Vehicle = Bicycle | Car; @@ -1017,23 +1000,23 @@ function travelToTexas(vehicle: Vehicle) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't over-optimize +### Не оптимізуйте надмірно -Modern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. There are good [resources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) for seeing where optimization is lacking. Target those in the meantime, until they are fixed if they can be. +Сучасні браузери виконують багато оптимізацій під капотом під час виконання. Часто, якщо ви оптимізуєте, ви просто витрачаєте свій час. Є хороші [ресурси](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) для перегляду, де оптимізація не вистачає. Націльтеся на них, поки вони не будуть виправлені, якщо це можливо. -**Bad:** +**Погано:** ```ts -// On old browsers, each iteration with uncached `list.length` would be costly -// because of `list.length` recomputation. In modern browsers, this is optimized. +// На старих браузерах кожна ітерація з незакешованою `list.length` була б дорогою +// через перераховування `list.length`. У сучасних браузерах це оптимізовано. for (let i = 0, len = list.length; i < len; i++) { // ... } ``` -**Good:** +**Добре:** ```ts for (let i = 0; i < list.length; i++) { @@ -1041,14 +1024,14 @@ for (let i = 0; i < list.length; i++) { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Remove dead code +### Видаляйте мертвий код -Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. -If it's not being called, get rid of it! It will still be saved in your version history if you still need it. +Мертвий код так само поганий, як і дублювання коду. Немає причин тримати його у вашій кодовій базі. +Якщо він не викликається, позбудьтеся його! Він все ще буде збережений у вашій історії версій, якщо вам він ще знадобиться. -**Bad:** +**Погано:** ```ts function oldRequestModule(url: string) { @@ -1063,7 +1046,7 @@ const req = requestModule; inventoryTracker('apples', req, 'www.inventory-awesome.io'); ``` -**Good:** +**Добре:** ```ts function requestModule(url: string) { @@ -1074,20 +1057,19 @@ const req = requestModule; inventoryTracker('apples', req, 'www.inventory-awesome.io'); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Use iterators and generators +### Використовуйте ітератори та генератори -Use generators and iterables when working with collections of data used like a stream. -There are some good reasons: +Використовуйте генератори та ітерабельні об'єкти при роботі з колекціями даних, що використовуються як потік. +На це є кілька причин: -- decouples the callee from the generator implementation in a sense that callee decides how many -items to access -- lazy execution, items are streamed on-demand -- built-in support for iterating items using the `for-of` syntax -- iterables allow implementing optimized iterator patterns +- відокремлює виклик від реалізації генератора в тому сенсі, що виклик вирішує, скільки елементів доступу +- лінива ініціалізація, елементи транслюються за запитом +- вбудована підтримка для ітерації елементів за допомогою синтаксису `for-of` +- ітерабельні об'єкти дозволяють реалізовувати оптимізовані шаблони ітератора -**Bad:** +**Погано:** ```ts function fibonacci(n: number): number[] { @@ -1106,15 +1088,15 @@ function print(n: number) { fibonacci(n).forEach(fib => console.log(fib)); } -// Print first 10 Fibonacci numbers. +// Виведення перших 10 чисел Фібоначчі. print(10); ``` -**Good:** +**Добре:** ```ts -// Generates an infinite stream of Fibonacci numbers. -// The generator doesn't keep the array of all numbers. +// Генерує нескінченний потік чисел Фібоначчі. +// Генератор не зберігає масив усіх чисел. function* fibonacci(): IterableIterator { let [a, b] = [0, 1]; @@ -1132,13 +1114,13 @@ function print(n: number) { } } -// Print first 10 Fibonacci numbers. +// Виведення перших 10 чисел Фібоначчі. print(10); ``` -There are libraries that allow working with iterables in a similar way as with native arrays, by -chaining methods like `map`, `slice`, `forEach` etc. See [itiriri](https://www.npmjs.com/package/itiriri) for -an example of advanced manipulation with iterables (or [itiriri-async](https://www.npmjs.com/package/itiriri-async) for manipulation of async iterables). +Існують бібліотеки, які дозволяють працювати з ітерабельними об'єктами аналогічно нативним масивам, шляхом +ланцюжка методів, таких як `map`, `slice`, `forEach` тощо. Дивіться [itiriri](https://www.npmjs.com/package/itiriri) для +прикладу розширеного маніпулювання з ітерабельними об'єктами (або [itiriri-async](https://www.npmjs.com/package/itiriri-async) для маніпуляцій з асинхронними ітерабельними об'єктами). ```ts import itiriri from 'itiriri'; @@ -1157,23 +1139,23 @@ itiriri(fibonacci()) .forEach(fib => console.log(fib)); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Objects and Data Structures +## Об'єкти та структури даних -### Use getters and setters +### Використовуйте геттери та сеттери -TypeScript supports getter/setter syntax. -Using getters and setters to access data from objects that encapsulate behavior could be better than simply looking for a property on an object. -"Why?" you might ask. Well, here's a list of reasons: +TypeScript підтримує синтаксис геттера/сеттера. +Використання геттерів і сеттерів для доступу до даних з об'єктів, які інкапсулюють поведінку, може бути кращим, ніж просто пошук властивості об'єкта. +"Чому?" ви можете запитати. Ось список причин: -- When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase. -- Makes adding validation simple when doing a `set`. -- Encapsulates the internal representation. -- Easy to add logging and error handling when getting and setting. -- You can lazy load your object's properties, let's say getting it from a server. +- Коли ви хочете зробити більше, ніж отримати властивість об'єкта, вам не потрібно шукати та змінювати кожен доступ у вашій кодовій базі. +- Робить додавання валідації простим при використанні `set`. +- Інкапсулює внутрішнє представлення. +- Легко додати логування та обробку помилок при отриманні та встановленні. +- Ви можете лінива завантажувати властивості вашого об'єкта, наприклад, отримуючи їх з сервера. -**Bad:** +**Погано:** ```ts type BankAccount = { @@ -1194,7 +1176,7 @@ if (value < 0) { account.balance = value; ``` -**Good:** +**Добре:** ```ts class BankAccount { @@ -1215,21 +1197,21 @@ class BankAccount { // ... } -// Now `BankAccount` encapsulates the validation logic. -// If one day the specifications change, and we need extra validation rule, -// we would have to alter only the `setter` implementation, -// leaving all dependent code unchanged. +// Тепер `BankAccount` інкапсулює логіку валідації. +// Якщо одного дня специфікації зміняться, і нам знадобиться додаткове правило валідації, +// нам потрібно буде змінити лише реалізацію `setter`, +// залишаючи весь залежний код незмішним. const account = new BankAccount(); account.balance = 100; ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Make objects have private/protected members +### Створюйте об'єкти з приватними/захищеними членами -TypeScript supports `public` *(default)*, `protected` and `private` accessors on class members. +TypeScript підтримує `public` *(за замовчуванням)*, `protected` та `private` модифікатори доступу для членів класу. -**Bad:** +**Погано:** ```ts class Circle { @@ -1249,7 +1231,7 @@ class Circle { } ``` -**Good:** +**Добре:** ```ts class Circle { @@ -1266,14 +1248,14 @@ class Circle { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Prefer immutability +### Віддавайте перевагу незмінності -TypeScript's type system allows you to mark individual properties on an interface/class as *readonly*. This allows you to work in a functional way (an unexpected mutation is bad). -For more advanced scenarios there is a built-in type `Readonly` that takes a type `T` and marks all of its properties as readonly using mapped types (see [mapped types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)). +Система типів TypeScript дозволяє позначати окремі властивості в інтерфейсі/класі як *readonly*. Це дозволяє працювати у функціональному стилі (несподівана мутація є поганою практикою). +Для більш складних сценаріїв існує вбудований тип `Readonly`, який приймає тип `T` і позначає всі його властивості як readonly, використовуючи відображені типи (див. [відображені типи](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)). -**Bad:** +**Погано:** ```ts interface Config { @@ -1283,7 +1265,7 @@ interface Config { } ``` -**Good:** +**Добре:** ```ts interface Config { @@ -1293,85 +1275,85 @@ interface Config { } ``` -For arrays, you can create a read-only array by using `ReadonlyArray`. -It doesn't allow changes such as `push()` and `fill()`, but can use features such as `concat()` and `slice()` that do not change the array's value. +Для масивів ви можете створити масив тільки для читання, використовуючи `ReadonlyArray`. +Він не дозволяє зміни, такі як `push()` та `fill()`, але можна використовувати функції, такі як `concat()` та `slice()`, які не змінюють значення масиву. -**Bad:** +**Погано:** ```ts const array: number[] = [ 1, 3, 5 ]; -array = []; // error -array.push(100); // array will be updated +array = []; // помилка +array.push(100); // масив буде оновлено ``` -**Good:** +**Добре:** ```ts const array: ReadonlyArray = [ 1, 3, 5 ]; -array = []; // error -array.push(100); // error +array = []; // помилка +array.push(100); // помилка ``` -Declaring read-only arguments in [TypeScript 3.4 is a bit easier](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#improvements-for-readonlyarray-and-readonly-tuples). +Оголошення аргументів лише для читання у [TypeScript 3.4 є трохи простішим](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#improvements-for-readonlyarray-and-readonly-tuples). ```ts function hoge(args: readonly string[]) { - args.push(1); // error + args.push(1); // помилка } ``` -Prefer [const assertions](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#const-assertions) for literal values. +Віддавайте перевагу [константним твердженням](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#const-assertions) для літеральних значень. -**Bad:** +**Погано:** ```ts const config = { hello: 'world' }; -config.hello = 'world'; // value is changed +config.hello = 'world'; // значення змінюється const array = [ 1, 3, 5 ]; -array[0] = 10; // value is changed +array[0] = 10; // значення змінюється -// writable objects is returned +// повертаються об'єкти, які можна змінювати function readonlyData(value: number) { return { value }; } const result = readonlyData(100); -result.value = 200; // value is changed +result.value = 200; // значення змінюється ``` -**Good:** +**Добре:** ```ts -// read-only object +// об'єкт тільки для читання const config = { hello: 'world' } as const; -config.hello = 'world'; // error +config.hello = 'world'; // помилка -// read-only array +// масив тільки для читання const array = [ 1, 3, 5 ] as const; -array[0] = 10; // error +array[0] = 10; // помилка -// You can return read-only objects +// Ви можете повертати об'єкти тільки для читання function readonlyData(value: number) { return { value } as const; } const result = readonlyData(100); -result.value = 200; // error +result.value = 200; // помилка ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### type vs. interface +### type проти interface -Use type when you might need a union or intersection. Use an interface when you want `extends` or `implements`. There is no strict rule, however, use the one that works for you. -For a more detailed explanation refer to this [answer](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/54101543#54101543) about the differences between `type` and `interface` in TypeScript. +Використовуйте type, коли вам може знадобитися об'єднання або перетин. Використовуйте interface, коли ви хочете використовувати `extends` або `implements`. Немає строгого правила, проте використовуйте те, що працює для вас. +Для більш детального пояснення зверніться до цієї [відповіді](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types/54101543#54101543) про відмінності між `type` і `interface` у TypeScript. -**Bad:** +**Погано:** ```ts interface EmailConfig { @@ -1393,7 +1375,7 @@ type Shape = { } ``` -**Good:** +**Добре:** ```ts @@ -1422,15 +1404,15 @@ class Square implements Shape { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Classes +## Класи -### Classes should be small +### Класи повинні бути малими -The class' size is measured by its responsibility. Following the *Single Responsibility principle* a class should be small. +Розмір класу вимірюється його відповідальністю. Слідуючи *принципу єдиної відповідальності*, клас повинен бути малим. -**Bad:** +**Погано:** ```ts class Dashboard { @@ -1453,7 +1435,7 @@ class Dashboard { ``` -**Good:** +**Добре:** ```ts class Dashboard { @@ -1462,29 +1444,29 @@ class Dashboard { getVersion(): string { /* ... */ } } -// split the responsibilities by moving the remaining methods to other classes +// розділіть відповідальності, переміщуючи решту методів до інших класів // ... ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### High cohesion and low coupling +### Висока згуртованість і низька зв'язність -Cohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method. -We then say that the class is *maximally cohesive*. In practice, this, however, is not always possible, nor even advisable. You should however prefer cohesion to be high. +Згуртованість визначає ступінь зв'язку між членами класу. В ідеалі всі поля в класі повинні використовуватися кожним методом. +Тоді ми кажемо, що клас є *максимально згуртованим*. На практиці, однак, це не завжди можливо і навіть не завжди рекомендується. Проте варто віддавати перевагу високій згуртованості. -Coupling refers to how related or dependent are two classes toward each other. Classes are said to be low coupled if changes in one of them don't affect the other one. +Зв'язність відноситься до того, наскільки пов'язані або залежні один від одного два класи. Класи вважаються слабо зв'язаними, якщо зміни в одному з них не впливають на інший. -Good software design has **high cohesion** and **low coupling**. +Хороший дизайн програмного забезпечення має **високу згуртованість** і **низьку зв'язність**. -**Bad:** +**Погано:** ```ts class UserManager { - // Bad: each private variable is used by one or another group of methods. - // It makes clear evidence that the class is holding more than a single responsibility. - // If I need only to create the service to get the transactions for a user, - // I'm still forced to pass and instance of `emailSender`. + // Погано: кожна приватна змінна використовується однією або іншою групою методів. + // Це ясно свідчить про те, що клас має більше однієї відповідальності. + // Якщо мені потрібно лише створити сервіс для отримання транзакцій для користувача, + // мене все одно змушують передавати екземпляр `emailSender`. constructor( private readonly db: Database, private readonly emailSender: EmailSender) { @@ -1512,7 +1494,7 @@ class UserManager { } ``` -**Good:** +**Добре:** ```ts class UserService { @@ -1546,21 +1528,21 @@ class UserNotifier { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Prefer composition over inheritance +### Віддавайте перевагу композиції перед успадкуванням -As stated famously in [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, you should *prefer composition over inheritance* where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can. +Як відомо зазначено в [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) від Gang of Four, ви повинні *віддавати перевагу композиції перед успадкуванням*, де це можливо. Є багато вагомих причин використовувати успадкування і багато вагомих причин використовувати композицію. Головна ідея цієї максими полягає в тому, що якщо ваш розум інстинктивно тяжіє до успадкування, спробуйте подумати, чи композиція може краще змоделювати вашу проблему. У деяких випадках це можливо. -You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition: +Ви можете запитати, "коли я повинен використовувати успадкування?" Це залежить від вашої конкретної проблеми, але ось гідний список випадків, коли успадкування має більше сенсу, ніж композиція: -1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails). +1. Ваше успадкування представляє відносини "є" (is-a), а не "має" (has-a) (Людина->Тварина проти Користувач->Дані користувача). -2. You can reuse code from the base classes (Humans can move like all animals). +2. Ви можете повторно використовувати код з базових класів (Люди можуть рухатися, як всі тварини). -3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move). +3. Ви хочете вносити глобальні зміни в похідні класи, змінюючи базовий клас (Змінити витрати калорій усіх тварин під час руху). -**Bad:** +**Погано:** ```ts class Employee { @@ -1572,7 +1554,7 @@ class Employee { // ... } -// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee +// Погано, тому що у працівників "є" податкові дані. EmployeeTaxData не є типом Employee class EmployeeTaxData extends Employee { constructor( name: string, @@ -1586,7 +1568,7 @@ class EmployeeTaxData extends Employee { } ``` -**Good:** +**Добре:** ```ts class Employee { @@ -1615,13 +1597,13 @@ class EmployeeTaxData { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Use method chaining +### Використовуйте ланцюжок методів -This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be. +Цей патерн дуже корисний і часто використовується в багатьох бібліотеках. Він дозволяє вашому коду бути виразним і менш багатослівним. З цієї причини використовуйте ланцюжки методів і подивіться, наскільки чистим буде ваш код. -**Bad:** +**Погано:** ```ts class QueryBuilder { @@ -1658,7 +1640,7 @@ queryBuilder.orderBy('firstName', 'lastName'); const query = queryBuilder.build(); ``` -**Good:** +**Добре:** ```ts class QueryBuilder { @@ -1697,15 +1679,15 @@ const query = new QueryBuilder() .build(); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** ## SOLID -### Single Responsibility Principle (SRP) +### Принцип єдиної відповідальності (SRP) -As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of time you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase. +Як зазначено в Clean Code, "Ніколи не повинно бути більше однієї причини для зміни класу". Спокусливо набити клас великою кількістю функціональності, як коли ви можете взяти лише одну валізу на ваш рейс. Проблема в тому, що ваш клас не буде концептуально згуртованим і це дасть йому багато причин для змін. Зменшення кількості необхідних змін класу важливе. Це важливо, тому що якщо занадто багато функціональності в одному класі і ви змінюєте частину його, може бути важко зрозуміти, як це вплине на інші залежні модулі у вашому кодовій базі. -**Bad:** +**Погано:** ```ts class UserSettings { @@ -1724,7 +1706,7 @@ class UserSettings { } ``` -**Good:** +**Добре:** ```ts class UserAuth { @@ -1752,13 +1734,13 @@ class UserSettings { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Open/Closed Principle (OCP) +### Принцип відкритості/закритості (OCP) -As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code. +Як зазначив Бертран Мейєр, "програмні сутності (класи, модулі, функції тощо) повинні бути відкритими для розширення, але закритими для модифікації". Що це означає? Цей принцип в основному стверджує, що ви повинні дозволяти користувачам додавати нові функціональні можливості без зміни існуючого коду. -**Bad:** +**Погано:** ```ts class AjaxAdapter extends Adapter { @@ -1784,30 +1766,30 @@ class HttpRequester { async fetch(url: string): Promise { if (this.adapter instanceof AjaxAdapter) { const response = await makeAjaxCall(url); - // transform response and return + // трансформувати відповідь і повернути } else if (this.adapter instanceof NodeAdapter) { const response = await makeHttpCall(url); - // transform response and return + // трансформувати відповідь і повернути } } } function makeAjaxCall(url: string): Promise { - // request and return promise + // запит і повернення обіцянки } function makeHttpCall(url: string): Promise { - // request and return promise + // запит і повернення обіцянки } ``` -**Good:** +**Добре:** ```ts abstract class Adapter { abstract async request(url: string): Promise; - // code shared to subclasses ... + // код, спільний для підкласів ... } class AjaxAdapter extends Adapter { @@ -1816,7 +1798,7 @@ class AjaxAdapter extends Adapter { } async request(url: string): Promise{ - // request and return promise + // запит і повернення обіцянки } // ... @@ -1828,7 +1810,7 @@ class NodeAdapter extends Adapter { } async request(url: string): Promise{ - // request and return promise + // запит і повернення обіцянки } // ... @@ -1840,20 +1822,20 @@ class HttpRequester { async fetch(url: string): Promise { const response = await this.adapter.request(url); - // transform response and return + // трансформувати відповідь і повернути } } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Liskov Substitution Principle (LSP) +### Принцип підстановки Лісков (LSP) -This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition. +Це страшний термін для дуже простої концепції. Формально він визначається як "Якщо S є підтипом T, то об'єкти типу T можуть бути замінені об'єктами типу S (тобто об'єкти типу S можуть замінити об'єкти типу T) без зміни будь-яких бажаних властивостей цієї програми (коректність, виконувані завдання тощо)". Це ще страшніше визначення. -The best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble. +Найкраще пояснення полягає в тому, що якщо у вас є батьківський клас і дочірній клас, то батьківський клас і дочірній клас можуть бути взаємозамінними без отримання неправильних результатів. Це все ще може бути незрозуміло, тому давайте розглянемо класичний приклад квадрата і прямокутника. Математично квадрат є прямокутником, але якщо ви моделюєте його за допомогою відносин "є" через успадкування, ви швидко потрапляєте в біду. -**Bad:** +**Погано:** ```ts class Rectangle { @@ -1905,7 +1887,7 @@ function renderLargeRectangles(rectangles: Rectangle[]) { const area = rectangle .setWidth(4) .setHeight(5) - .getArea(); // BAD: Returns 25 for Square. Should be 20. + .getArea(); // ПОГАНО: Повертає 25 для Square. Повинно бути 20. rectangle.render(area); }); } @@ -1914,7 +1896,7 @@ const rectangles = [new Rectangle(), new Rectangle(), new Square()]; renderLargeRectangles(rectangles); ``` -**Good:** +**Добре:** ```ts abstract class Shape { @@ -1962,14 +1944,14 @@ const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; renderLargeShapes(shapes); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Interface Segregation Principle (ISP) +### Принцип розділення інтерфейсу (ISP) -ISP states that "Clients should not be forced to depend upon interfaces that they do not use.". This principle is very much related to the Single Responsibility Principle. -What it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they don’t actually need. +ISP стверджує, що "Клієнти не повинні бути змушені залежати від інтерфейсів, які вони не використовують". Цей принцип дуже пов'язаний з принципом єдиної відповідальності. +Що це дійсно означає, так це те, що ви завжди повинні проектувати свої абстракції таким чином, щоб клієнти, які використовують відкриті методи, не отримували весь пиріг. Це також включає в себе накладання на клієнтів тягаря реалізації методів, які їм насправді не потрібні. -**Bad:** +**Погано:** ```ts interface SmartPrinter { @@ -2007,7 +1989,7 @@ class EconomicPrinter implements SmartPrinter { } ``` -**Good:** +**Добре:** ```ts interface Printer { @@ -2043,21 +2025,21 @@ class EconomicPrinter implements Printer { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Dependency Inversion Principle (DIP) +### Принцип інверсії залежностей (DIP) -This principle states two essential things: +Цей принцип стверджує дві суттєві речі: -1. High-level modules should not depend on low-level modules. Both should depend on abstractions. +1. Модулі високого рівня не повинні залежати від модулів низького рівня. Обидва повинні залежати від абстракцій. -2. Abstractions should not depend upon details. Details should depend on abstractions. +2. Абстракції не повинні залежати від деталей. Деталі повинні залежати від абстракцій. -This can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor. - -DIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript is [InversifyJs](https://www.npmjs.com/package/inversify) +Це може бути важко зрозуміти спочатку, але якщо ви працювали з Angular, ви бачили реалізацію цього принципу у вигляді впровадження залежностей (DI). Хоча це не ідентичні концепції, DIP утримує модулі високого рівня від знання деталей їхніх модулів низького рівня та їх налаштування. Це можна досягти через DI. Величезною перевагою цього є зменшення зв'язку між модулями. Зв'язування - це дуже погана схема розробки, оскільки вона робить ваш код важким для рефакторингу. -**Bad:** +DIP зазвичай досягається за допомогою контейнера інверсії управління (IoC). Прикладом потужного IoC-контейнера для TypeScript є [InversifyJs](https://www.npmjs.com/package/inversify) + +**Погано:** ```ts import { readFile as readFileCb } from 'fs'; @@ -2071,14 +2053,14 @@ type ReportData = { class XmlFormatter { parse(content: string): T { - // Converts an XML string to an object T + // Перетворює рядок XML на об'єкт T } } class ReportReader { - // BAD: We have created a dependency on a specific request implementation. - // We should just have ReportReader depend on a parse method: `parse` + // ПОГАНО: Ми створили залежність від конкретної реалізації запиту. + // Нам слід просто зробити так, щоб ReportReader залежав від методу parse: `parse` private readonly formatter = new XmlFormatter(); async read(path: string): Promise { @@ -2092,7 +2074,7 @@ const reader = new ReportReader(); const report = await reader.read('report.xml'); ``` -**Good:** +**Добре:** ```ts import { readFile as readFileCb } from 'fs'; @@ -2110,14 +2092,14 @@ interface Formatter { class XmlFormatter implements Formatter { parse(content: string): T { - // Converts an XML string to an object T + // Перетворює рядок XML на об'єкт T } } class JsonFormatter implements Formatter { parse(content: string): T { - // Converts a JSON string to an object T + // Перетворює рядок JSON на об'єкт T } } @@ -2135,52 +2117,52 @@ class ReportReader { const reader = new ReportReader(new XmlFormatter()); const report = await reader.read('report.xml'); -// or if we had to read a json report +// або якщо нам потрібно прочитати json звіт const reader = new ReportReader(new JsonFormatter()); const report = await reader.read('report.json'); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Testing +## Тестування -Testing is more important than shipping. If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you didn't break anything. -Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) -is how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a good [coverage tool](https://github.com/gotwarlost/istanbul). +Тестування є важливішим за доставку. Якщо у вас немає тестів або їх недостатньо, кожного разу, коли ви доставляєте код, ви не будете впевнені, що нічого не зламали. +Вирішення того, що становить достатню кількість, залежить від вашої команди, але 100% покриття (всі оператори та гілки) +- це спосіб досягти дуже високої впевненості та спокою розробників. Це означає, що крім наявності чудового фреймворку для тестування, вам також потрібно використовувати хороший [інструмент покриття](https://github.com/gotwarlost/istanbul). -There's no excuse to not write tests. There are [plenty of good JS test frameworks](http://jstherightway.org/#testing-tools) with typings support for TypeScript, so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one. +Немає виправдання не писати тести. Існує [багато хороших JS-фреймворків для тестування](http://jstherightway.org/#testing-tools) з підтримкою типізації для TypeScript, тому знайдіть той, який підходить вашій команді. Коли ви знайдете один, що працює для вашої команди, тоді намагайтеся завжди писати тести для кожної нової функції/модуля, який ви вводите. Якщо ваш переважний метод - це розробка через тестування (TDD), це чудово, але головне - просто переконатися, що ви досягаєте своїх цілей з покриття перед запуском будь-якої функції або рефакторингом існуючої. -### The three laws of TDD +### Три закони TDD -1. You are not allowed to write any production code unless it is to make a failing unit test pass. +1. Вам не дозволяється писати виробничий код, якщо це не для того, щоб пройти модульний тест, що не проходить. -2. You are not allowed to write any more of a unit test than is sufficient to fail, and; compilation failures are failures. +2. Вам не дозволяється писати більше модульного тесту, ніж достатньо для невдачі, і; помилки компіляції - це невдачі. -3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test. +3. Вам не дозволяється писати більше виробничого коду, ніж достатньо для проходження одного невдалого модульного тесту. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### F.I.R.S.T. rules +### Правила F.I.R.S.T. -Clean tests should follow the rules: +Чисті тести повинні дотримуватися таких правил: -- **Fast** tests should be fast because we want to run them frequently. +- **Fast** (Швидкі) тести повинні бути швидкими, тому що ми хочемо запускати їх часто. -- **Independent** tests should not depend on each other. They should provide same output whether run independently or all together in any order. +- **Independent** (Незалежні) тести не повинні залежати один від одного. Вони повинні давати однаковий результат незалежно від того, запускаються вони окремо чи всі разом у будь-якому порядку. -- **Repeatable** tests should be repeatable in any environment and there should be no excuse for why they fail. +- **Repeatable** (Повторювані) тести повинні бути повторюваними в будь-якому середовищі, і не повинно бути виправдання, чому вони провалюються. -- **Self-Validating** a test should answer with either *Passed* or *Failed*. You don't need to compare log files to answer if a test passed. +- **Self-Validating** (Самоперевірочні) тест повинен відповідати або *Пройдено*, або *Не пройдено*. Вам не потрібно порівнювати файли журналів, щоб відповісти, чи пройшов тест. -- **Timely** unit tests should be written before the production code. If you write tests after the production code, you might find writing tests too hard. +- **Timely** (Своєчасні) модульні тести повинні бути написані до виробничого коду. Якщо ви пишете тести після виробничого коду, ви можете виявити, що написання тестів занадто складне. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Single concept per test +### Одна концепція на тест -Tests should also follow the *Single Responsibility Principle*. Make only one assert per unit test. +Тести також повинні слідувати *Принципу єдиної відповідальності*. Робіть лише одне твердження на модульний тест. -**Bad:** +**Погано:** ```ts import { assert } from 'chai'; @@ -2201,7 +2183,7 @@ describe('AwesomeDate', () => { }); ``` -**Good:** +**Добре:** ```ts import { assert } from 'chai'; @@ -2224,13 +2206,13 @@ describe('AwesomeDate', () => { }); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### The name of the test should reveal its intention +### Назва тесту повинна розкривати його намір -When a test fails, its name is the first indication of what may have gone wrong. +Коли тест не проходить, його назва є першим показником того, що могло піти не так. -**Bad:** +**Погано:** ```ts describe('Calendar', () => { @@ -2244,7 +2226,7 @@ describe('Calendar', () => { }); ``` -**Good:** +**Добре:** ```ts describe('Calendar', () => { @@ -2258,17 +2240,17 @@ describe('Calendar', () => { }); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Concurrency +## Асинхронність -### Prefer promises vs callbacks +### Перевага обіцянок (promises) перед зворотними викликами (callbacks) -Callbacks aren't clean, and they cause excessive amounts of nesting *(the callback hell)*. -There are utilities that transform existing functions using the callback style to a version that returns promises -(for Node.js see [`util.promisify`](https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original), for general purpose see [pify](https://www.npmjs.com/package/pify), [es6-promisify](https://www.npmjs.com/package/es6-promisify)) +Зворотні виклики не є чистими, і вони спричиняють надмірну кількість вкладеності *(пекло зворотних викликів)*. +Існують утиліти, які перетворюють існуючі функції, що використовують зворотні виклики, на версію, яка повертає обіцянки +(для Node.js див. [`util.promisify`](https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original), для загального призначення див. [pify](https://www.npmjs.com/package/pify), [es6-promisify](https://www.npmjs.com/package/es6-promisify)) -**Bad:** +**Погано:** ```ts import { get } from 'request'; @@ -2299,7 +2281,7 @@ downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html' }); ``` -**Good:** +**Добре:** ```ts import { get } from 'request'; @@ -2318,24 +2300,24 @@ downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html' .catch(error => console.error(error)); ``` -Promises supports a few helper methods that help make code more concise: +Обіцянки підтримують кілька допоміжних методів, які допомагають зробити код більш стислим: -| Pattern | Description | +| Шаблон | Опис | | ------------------------ | ----------------------------------------- | -| `Promise.resolve(value)` | Convert a value into a resolved promise. | -| `Promise.reject(error)` | Convert an error into a rejected promise. | -| `Promise.all(promises)` | Returns a new promise which is fulfilled with an array of fulfillment values for the passed promises or rejects with the reason of the first promise that rejects. | -| `Promise.race(promises)`| Returns a new promise which is fulfilled/rejected with the result/error of the first settled promise from the array of passed promises. | +| `Promise.resolve(value)` | Перетворює значення в вирішену обіцянку. | +| `Promise.reject(error)` | Перетворює помилку в відхилену обіцянку. | +| `Promise.all(promises)` | Повертає нову обіцянку, яка виконується з масивом значень виконання для переданих обіцянок або відхиляється з причиною першої обіцянки, яка відхиляється. | +| `Promise.race(promises)`| Повертає нову обіцянку, яка виконується/відхиляється з результатом/помилкою першої врегульованої обіцянки з масиву переданих обіцянок. | -`Promise.all` is especially useful when there is a need to run tasks in parallel. `Promise.race` makes it easier to implement things like timeouts for promises. +`Promise.all` особливо корисний, коли існує потреба запускати завдання паралельно. `Promise.race` полегшує реалізацію таких речей, як тайм-аути для обіцянок. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Async/Await are even cleaner than Promises +### Async/Await ще чистіші за обіцянки -With `async`/`await` syntax you can write code that is far cleaner and more understandable than chained promises. Within a function prefixed with `async` keyword, you have a way to tell the JavaScript runtime to pause the execution of code on the `await` keyword (when used on a promise). +З синтаксисом `async`/`await` ви можете писати код, який є набагато чистішим та зрозумілішим, ніж ланцюжки обіцянок. У функції з префіксом ключового слова `async` у вас є спосіб сказати середовищу виконання JavaScript призупинити виконання коду на ключовому слові `await` (коли воно використовується з обіцянкою). -**Bad:** +**Погано:** ```ts import { get } from 'request'; @@ -2353,7 +2335,7 @@ downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html' .catch(error => console.error(error)); ``` -**Good:** +**Добре:** ```ts import { get } from 'request'; @@ -2367,7 +2349,7 @@ async function downloadPage(url: string): Promise { return response; } -// somewhere in an async function +// десь в асинхронній функції try { const content = await downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin'); await write('article.html', content); @@ -2377,22 +2359,21 @@ try { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Error Handling +## Обробка помилок -Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping function -execution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace. +Викинуті помилки - це хороша річ! Вони означають, що середовище виконання успішно визначило, коли щось у вашій програмі пішло не так, і воно повідомляє вам, зупиняючи виконання функції +в поточному стеку, завершуючи процес (у Node), та повідомляючи вас у консолі за допомогою сліду стеку. -### Always use Error for throwing or rejecting +### Завжди використовуйте Error для викидання чи відхилення -JavaScript as well as TypeScript allow you to `throw` any object. A Promise can also be rejected with any reason object. -It is advisable to use the `throw` syntax with an `Error` type. This is because your error might be caught in higher level code with a `catch` syntax. -It would be very confusing to catch a string message there and would make -[debugging more painful](https://basarat.gitbook.io/typescript/type-system/exceptions#always-use-error). -For the same reason you should reject promises with `Error` types. +JavaScript, а також TypeScript дозволяють вам `throw` будь-який об'єкт. Обіцянка також може бути відхилена з будь-якою причиною об'єкта. +Рекомендується використовувати синтаксис `throw` з типом `Error`. Це тому, що ваша помилка може бути перехоплена у коді вищого рівня з синтаксисом `catch`. +Було б дуже заплутано перехопити там текстове повідомлення, і це зробило б [налагодження більш болісним](https://basarat.gitbook.io/typescript/type-system/exceptions#always-use-error). +З тієї ж причини ви повинні відхиляти обіцянки з типами `Error`. -**Bad:** +**Погано:** ```ts function calculateTotal(items: Item[]): number { @@ -2404,7 +2385,7 @@ function get(): Promise { } ``` -**Good:** +**Добре:** ```ts function calculateTotal(items: Item[]): number { @@ -2415,17 +2396,16 @@ function get(): Promise { return Promise.reject(new Error('Not implemented.')); } -// or equivalent to: +// або еквівалентно до: async function get(): Promise { throw new Error('Not implemented.'); } ``` -The benefit of using `Error` types is that it is supported by the syntax `try/catch/finally` and implicitly all errors have the `stack` property which -is very powerful for debugging. -There are also other alternatives, not to use the `throw` syntax and instead always return custom error objects. TypeScript makes this even easier. -Consider the following example: +Перевага використання типів `Error` полягає в тому, що вони підтримуються синтаксисом `try/catch/finally`, і неявно всі помилки мають властивість `stack`, яка +дуже потужна для налагодження. +Існують також інші альтернативи, не використовувати синтаксис `throw`, а замість цього завжди повертати користувацькі об'єкти помилок. TypeScript полегшує це. Розгляньте наступний приклад: ```ts type Result = { isError: false, value: R }; @@ -2442,15 +2422,15 @@ function calculateTotal(items: Item[]): Failable { } ``` -For the detailed explanation of this idea refer to the [original post](https://medium.com/@dhruvrajvanshi/making-exceptions-type-safe-in-typescript-c4d200ee78e9). +Для детального пояснення цієї ідеї зверніться до [оригінального посту](https://medium.com/@dhruvrajvanshi/making-exceptions-type-safe-in-typescript-c4d200ee78e9). -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't ignore caught errors +### Не ігноруйте перехоплені помилки -Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (`console.log`) isn't much better as often it can get lost in a sea of things printed to the console. If you wrap any bit of code in a `try/catch` it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs. +Нічого не робити з перехопленою помилкою не дає вам можливості виправити або реагувати на цю помилку. Запис помилки в консоль (`console.log`) не набагато краще, оскільки часто вона може губитися в морі речей, виведених на консоль. Якщо ви обгортаєте будь-який фрагмент коду в `try/catch`, це означає, що ви думаєте, що там може виникнути помилка, і тому у вас повинен бути план або шлях коду для випадку, коли вона виникає. -**Bad:** +**Погано:** ```ts try { @@ -2459,16 +2439,16 @@ try { console.log(error); } -// or even worse +// або ще гірше try { functionThatMightThrow(); } catch (error) { - // ignore error + // ігнорувати помилку } ``` -**Good:** +**Добре:** ```ts import { logger } from './logging' @@ -2480,13 +2460,13 @@ try { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't ignore rejected promises +### Не ігноруйте відхилені обіцянки -For the same reason you shouldn't ignore caught errors from `try/catch`. +З тієї ж причини ви не повинні ігнорувати перехоплені помилки з `try/catch`. -**Bad:** +**Погано:** ```ts getUser() @@ -2498,7 +2478,7 @@ getUser() }); ``` -**Good:** +**Добре:** ```ts import { logger } from './logging' @@ -2511,7 +2491,7 @@ getUser() logger.log(error); }); -// or using the async/await syntax: +// або використовуючи синтаксис async/await: try { const user = await getUser(); @@ -2521,31 +2501,31 @@ try { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Formatting +## Форматування -Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is *DO NOT ARGUE* over formatting. There are tons of tools to automate this. Use one! It's a waste of time and money for engineers to argue over formatting. The general rule to follow is *keep consistent formatting rules*. +Форматування є суб'єктивним. Як і багато правил тут, немає жорсткого і швидкого правила, якого ви повинні дотримуватися. Головна точка - *НЕ СПЕРЕЧАТИСЯ* про форматування. Існує безліч інструментів для автоматизації цього. Використовуйте один! Це марнування часу і грошей для інженерів сперечатися про форматування. Загальне правило, якого слід дотримуватися, - *зберігати послідовні правила форматування*. -For TypeScript there is a powerful tool called [ESLint](https://typescript-eslint.io/). It's a static analysis tool that can help you improve dramatically the readability and maintainability of your code. There are ready to use ESLint configurations that you can reference in your projects: +Для TypeScript існує потужний інструмент під назвою [ESLint](https://typescript-eslint.io/). Це інструмент статичного аналізу, який може допомогти вам кардинально покращити читабельність та обслуговуваність вашого коду. Існують готові до використання конфігурації ESLint, на які ви можете посилатися у своїх проектах: -- [ESLint Config Airbnb](https://www.npmjs.com/package/eslint-config-airbnb-typescript) - Airbnb style guide +- [ESLint Config Airbnb](https://www.npmjs.com/package/eslint-config-airbnb-typescript) - Стиль Airbnb -- [ESLint Base Style Config](https://www.npmjs.com/package/eslint-plugin-base-style-config) - a Set of Essential ESLint rules for JS, TS and React +- [ESLint Base Style Config](https://www.npmjs.com/package/eslint-plugin-base-style-config) - Набір основних правил ESLint для JS, TS та React -- [ESLint + Prettier](https://www.npmjs.com/package/eslint-config-prettier) - lint rules for [Prettier](https://github.com/prettier/prettier) code formatter +- [ESLint + Prettier](https://www.npmjs.com/package/eslint-config-prettier) - правила lint для форматера коду [Prettier](https://github.com/prettier/prettier) -Refer also to this great [TypeScript StyleGuide and Coding Conventions](https://basarat.gitbook.io/typescript/styleguide) source. +Зверніться також до цього чудового джерела [TypeScript StyleGuide and Coding Conventions](https://basarat.gitbook.io/typescript/styleguide). -### Migrating from TSLint to ESLint +### Міграція з TSLint на ESLint -If you are looking for help in migrating from TSLint to ESLint, you can check out this project: +Якщо ви шукаєте допомогу в міграції з TSLint на ESLint, ви можете перевірити цей проект: -### Use consistent capitalization +### Використовуйте послідовну капіталізацію -Capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just *be consistent*. +Капіталізація розповідає вам багато про ваші змінні, функції тощо. Ці правила є суб'єктивними, тому ваша команда може вибрати те, що захоче. Суть в тому, що незалежно від того, що ви всі виберете, просто *будьте послідовними*. -**Bad:** +**Погано:** ```ts const DAYS_IN_WEEK = 7; @@ -2561,7 +2541,7 @@ type animal = { /* ... */ } type Container = { /* ... */ } ``` -**Good:** +**Добре:** ```ts const DAYS_IN_WEEK = 7; @@ -2580,18 +2560,18 @@ type Animal = { /* ... */ } type Container = { /* ... */ } ``` -Prefer using `PascalCase` for class, interface, type and namespace names. -Prefer using `camelCase` for variables, functions and class members. -Prefer using capitalized `SNAKE_CASE` for constants. +Перевагу слід віддавати використанню `PascalCase` для назв класів, інтерфейсів, типів та просторів імен. +Перевагу слід віддавати використанню `camelCase` для змінних, функцій та членів класів. +Перевагу слід віддавати використанню капіталізованого `SNAKE_CASE` для констант. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Function callers and callees should be close +### Функції-викликачі та функції-виклики повинні бути близькими -If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee. -We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way. +Якщо функція викликає іншу, тримайте ці функції вертикально близько в вихідному файлі. В ідеалі, тримайте викликача прямо над викликаним. +Ми зазвичай читаємо код зверху вниз, як газету. Через це, зробіть ваш код таким, що читається таким чином. -**Bad:** +**Погано:** ```ts class PerformanceReview { @@ -2632,7 +2612,7 @@ const review = new PerformanceReview(employee); review.review(); ``` -**Good:** +**Добре:** ```ts class PerformanceReview { @@ -2673,27 +2653,27 @@ const review = new PerformanceReview(employee); review.review(); ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Organize imports +### Організуйте імпорти -With clean and easy to read import statements you can quickly see the dependencies of current code. Make sure you apply following good practices for `import` statements: +З чистими та легкими для читання операторами імпорту ви можете швидко побачити залежності поточного коду. Переконайтеся, що ви застосовуєте наступні хороші практики для операторів `import`: -- Import statements should be alphabetized and grouped. -- Unused imports should be removed. -- Named imports must be alphabetized (i.e. `import {A, B, C} from 'foo';`) -- Import sources must be alphabetized within groups, i.e.: `import * as foo from 'a'; import * as bar from 'b';` -- Prefer using `import type` instead of `import` when importing only types from a file to avoid dependency cycles, as these imports are erased at runtime -- Groups of imports are delineated by blank lines. -- Groups must respect following order: - - Polyfills (i.e. `import 'reflect-metadata';`) - - Node builtin modules (i.e. `import fs from 'fs';`) - - external modules (i.e. `import { query } from 'itiriri';`) - - internal modules (i.e `import { UserService } from 'src/services/userService';`) - - modules from a parent directory (i.e. `import foo from '../foo'; import qux from '../../foo/qux';`) - - modules from the same or a sibling's directory (i.e. `import bar from './bar'; import baz from './bar/baz';`) +- Оператори імпорту повинні бути в алфавітному порядку та згруповані. +- Невикористані імпорти повинні бути видалені. +- Іменовані імпорти повинні бути в алфавітному порядку (тобто `import {A, B, C} from 'foo';`) +- Джерела імпорту повинні бути в алфавітному порядку в межах груп, тобто: `import * as foo from 'a'; import * as bar from 'b';` +- Перевагу слід віддавати використанню `import type` замість `import` при імпорті лише типів з файлу, щоб уникнути циклів залежностей, оскільки ці імпорти стираються під час виконання +- Групи імпорту розділяються порожніми рядками. +- Групи повинні поважати наступний порядок: + - Поліфіли (тобто `import 'reflect-metadata';`) + - Вбудовані модулі Node (тобто `import fs from 'fs';`) + - зовнішні модулі (тобто `import { query } from 'itiriri';`) + - внутрішні модулі (тобто `import { UserService } from 'src/services/userService';`) + - модулі з батьківського каталогу (тобто `import foo from '../foo'; import qux from '../../foo/qux';`) + - модулі з того ж або братнього каталогу (тобто `import bar from './bar'; import baz from './bar/baz';`) -**Bad:** +**Погано:** ```ts import { TypeDefinition } from '../types/typeDefinition'; @@ -2706,7 +2686,7 @@ import { BindingScopeEnum, Container } from 'inversify'; import 'reflect-metadata'; ``` -**Good:** +**Добре:** ```ts import 'reflect-metadata'; @@ -2722,21 +2702,21 @@ import { ApiCredentials, Adapters } from './common/api/authorization'; import { ConfigPlugin } from './plugins/config/configPlugin'; ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Use typescript aliases +### Використовуйте аліаси TypeScript -Create prettier imports by defining the paths and baseUrl properties in the compilerOptions section in the `tsconfig.json` +Створюйте більш зручні імпорти, визначаючи властивості paths та baseUrl у розділі compilerOptions у файлі `tsconfig.json` -This will avoid long relative paths when doing imports. +Це дозволить уникнути довгих відносних шляхів при імпорті. -**Bad:** +**Погано:** ```ts import { UserService } from '../../../services/UserService'; ``` -**Good:** +**Добре:** ```ts import { UserService } from '@services/UserService'; @@ -2756,40 +2736,40 @@ import { UserService } from '@services/UserService'; ... ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Comments +## Коментарі -The use of a comments is an indication of failure to express without them. Code should be the only source of truth. +Використання коментарів є ознакою неспроможності висловитися без них. Код повинен бути єдиним джерелом правди. -> Don’t comment bad code—rewrite it. +> Не коментуйте поганий код — перепишіть його. > — *Brian W. Kernighan and P. J. Plaugher* -### Prefer self explanatory code instead of comments +### Віддавайте перевагу самопояснюючому коду замість коментарів -Comments are an apology, not a requirement. Good code *mostly* documents itself. +Коментарі — це вибачення, а не вимога. Хороший код *здебільшого* документує сам себе. -**Bad:** +**Погано:** ```ts -// Check if subscription is active. +// Перевірити, чи підписка активна. if (subscription.endDate > Date.now) { } ``` -**Good:** +**Добре:** ```ts const isSubscriptionActive = subscription.endDate > Date.now; if (isSubscriptionActive) { /* ... */ } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't leave commented out code in your codebase +### Не залишайте закоментований код у своїй кодовій базі -Version control exists for a reason. Leave old code in your history. +Контроль версій існує не просто так. Залиште старий код у вашій історії. -**Bad:** +**Погано:** ```ts type User = { @@ -2800,7 +2780,7 @@ type User = { } ``` -**Good:** +**Добре:** ```ts type User = { @@ -2809,27 +2789,27 @@ type User = { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Don't have journal comments +### Не ведіть журнал у коментарях -Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Use `git log` to get history! +Пам'ятайте, використовуйте контроль версій! Немає потреби в мертвому коді, закоментованому коді, і особливо в коментарях-журналах. Використовуйте `git log`, щоб отримати історію! -**Bad:** +**Погано:** ```ts /** - * 2016-12-20: Removed monads, didn't understand them (RM) - * 2016-10-01: Improved using special monads (JP) - * 2016-02-03: Added type-checking (LI) - * 2015-03-14: Implemented combine (JR) + * 2016-12-20: Видалені монади, не зрозумів їх (RM) + * 2016-10-01: Покращено використання спеціальних монад (JP) + * 2016-02-03: Додано перевірку типів (LI) + * 2015-03-14: Реалізовано combine (JR) */ function combine(a: number, b: number): number { return a + b; } ``` -**Good:** +**Добре:** ```ts function combine(a: number, b: number): number { @@ -2837,18 +2817,18 @@ function combine(a: number, b: number): number { } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### Avoid positional markers +### Уникайте позиційних маркерів -They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code. -Most IDE support code folding feature that allows you to collapse/expand blocks of code (see Visual Studio Code [folding regions](https://code.visualstudio.com/updates/v1_17#_folding-regions)). +Вони зазвичай лише додають шуму. Нехай назви функцій та змінних разом з правильним відступом та форматуванням надають вашому коду візуальну структуру. +Більшість середовищ розробки підтримують функцію згортання коду, що дозволяє згортати/розгортати блоки коду (див. [згортання регіонів](https://code.visualstudio.com/updates/v1_17#_folding-regions) у Visual Studio Code). -**Bad:** +**Погано:** ```ts //////////////////////////////////////////////////////////////////////////////// -// Client class +// Клас клієнта //////////////////////////////////////////////////////////////////////////////// class Client { id: number; @@ -2857,14 +2837,14 @@ class Client { contact: Contact; //////////////////////////////////////////////////////////////////////////////// - // public methods + // публічні методи //////////////////////////////////////////////////////////////////////////////// public describe(): string { // ... } //////////////////////////////////////////////////////////////////////////////// - // private methods + // приватні методи //////////////////////////////////////////////////////////////////////////////// private describeAddress(): string { // ... @@ -2876,7 +2856,7 @@ class Client { }; ``` -**Good:** +**Добре:** ```ts class Client { @@ -2899,54 +2879,54 @@ class Client { }; ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -### TODO comments +### Коментарі TODO -When you find yourself that you need to leave notes in the code for some later improvements, -do that using `// TODO` comments. Most IDE have special support for those kinds of comments so that -you can quickly go over the entire list of todos. +Коли ви розумієте, що вам потрібно залишити нотатки в коді для пізніших вдосконалень, +робіть це за допомогою коментарів `// TODO`. Більшість IDE мають спеціальну підтримку таких коментарів, тому +ви можете швидко переглянути весь список todos. -Keep in mind however that a *TODO* comment is not an excuse for bad code. +Однак майте на увазі, що коментар *TODO* не є виправданням для поганого коду. -**Bad:** +**Погано:** ```ts function getActiveSubscriptions(): Promise { - // ensure `dueDate` is indexed. + // переконатися, що `dueDate` проіндексовано. return db.subscriptions.find({ dueDate: { $lte: new Date() } }); } ``` -**Good:** +**Добре:** ```ts function getActiveSubscriptions(): Promise { - // TODO: ensure `dueDate` is indexed. + // TODO: переконатися, що `dueDate` проіндексовано. return db.subscriptions.find({ dueDate: { $lte: new Date() } }); } ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)** -## Translations +## Переклади -This is also available in other languages: -- ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [vitorfreitas/clean-code-typescript](https://github.com/vitorfreitas/clean-code-typescript) -- ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese**: +Це також доступно іншими мовами: +- ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Бразильська португальська**: [vitorfreitas/clean-code-typescript](https://github.com/vitorfreitas/clean-code-typescript) +- ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Китайська**: - [beginor/clean-code-typescript](https://github.com/beginor/clean-code-typescript) - [pipiliang/clean-code-typescript](https://github.com/pipiliang/clean-code-typescript) -- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [ralflorent/clean-code-typescript](https://github.com/ralflorent/clean-code-typescript) -- ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [mheob/clean-code-typescript](https://github.com/mheob/clean-code-typescript) -- ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [MSakamaki/clean-code-typescript](https://github.com/MSakamaki/clean-code-typescript) -- ![ko](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [738/clean-code-typescript](https://github.com/738/clean-code-typescript) -- ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [Real001/clean-code-typescript](https://github.com/Real001/clean-code-typescript) -- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [3xp1o1t/clean-code-typescript](https://github.com/3xp1o1t/clean-code-typescript) -- ![tr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Turkey.png) **Turkish**: [ozanhonamlioglu/clean-code-typescript](https://github.com/ozanhonamlioglu/clean-code-typescript) -- ![vi](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnamese**: [hoangsetup/clean-code-typescript](https://github.com/hoangsetup/clean-code-typescript) +- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **Французька**: [ralflorent/clean-code-typescript](https://github.com/ralflorent/clean-code-typescript) +- ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **Німецька**: [mheob/clean-code-typescript](https://github.com/mheob/clean-code-typescript) +- ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Японська**: [MSakamaki/clean-code-typescript](https://github.com/MSakamaki/clean-code-typescript) +- ![ko](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Корейська**: [738/clean-code-typescript](https://github.com/738/clean-code-typescript) +- ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Російська**: [Real001/clean-code-typescript](https://github.com/Real001/clean-code-typescript) +- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Іспанська**: [3xp1o1t/clean-code-typescript](https://github.com/3xp1o1t/clean-code-typescript) +- ![tr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Turkey.png) **Турецька**: [ozanhonamlioglu/clean-code-typescript](https://github.com/ozanhonamlioglu/clean-code-typescript) +- ![vi](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **В'єтнамська**: [hoangsetup/clean-code-typescript](https://github.com/hoangsetup/clean-code-typescript) -References will be added once translations are completed. -Check this [discussion](https://github.com/labs42io/clean-code-typescript/issues/15) for more details and progress. -You can make an indispensable contribution to *Clean Code* community by translating this to your language. +Посилання будуть додані після завершення перекладів. +Перевірте цю [дискусію](https://github.com/labs42io/clean-code-typescript/issues/15) для отримання додаткових деталей та прогресу. +Ви можете зробити неоціненний внесок у спільноту *Clean Code*, переклавши це вашою мовою. -**[⬆ back to top](#table-of-contents)** +**[⬆ повернутись до змісту](#table-of-contents)**