Skip to content

Commit aabd08b

Browse files
authored
Merged tanslation of "Comments" by @alexgalkin.
Merged tanslation of "Comments" section made by @alexgalkin.
2 parents 4eada16 + e731e5a commit aabd08b

File tree

1 file changed

+70
-69
lines changed

1 file changed

+70
-69
lines changed
Lines changed: 70 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
1-
# Comments
1+
# Коментарі
22

3-
As we know from the chapter <info:structure>, comments can be single-line: starting with `//` and multiline: `/* ... */`.
3+
Як нам відомо з розділу <info:structure>, коментарі можна писати як на одному рядку: починаючи його з `//` так і на декількох рядках, розділяючи їх за допомогою `/* ... */`.
44

5-
We normally use them to describe how and why the code works.
5+
Зазвичай ми використовуємо коментарі для опису того, як і чому наш код працює.
66

7-
At first sight, commenting might be obvious, but novices in programming often use them wrongly.
7+
На перший погляд, коментування може здаватись очевидним, проте початківці часто використовують їх неправильно.
88

9-
## Bad comments
9+
## Погані коментарі
1010

11-
Novices tend to use comments to explain "what is going on in the code". Like this:
11+
Початківці намагаються використовувати коментарі, щоб пояснити "що саме відбувається у коді". Наприклад:
1212

1313
```js
14-
// This code will do this thing (...) and that thing (...)
15-
// ...and who knows what else...
16-
very;
17-
complex;
18-
code;
14+
// Цей код зробить це (...) а потім ось це (...)
15+
// ...і хто знає що ще...
16+
дуже;
17+
складний;
18+
код;
1919
```
2020

21-
But in good code, the amount of such "explanatory" comments should be minimal. Seriously, the code should be easy to understand without them.
21+
Проте в якісному коді, кількість таких "пояснювальних" коментарів повинна бути мінімальною. Серйозно, код повинен бути зрозумілим без них.
2222

23-
There's a great rule about that: "if the code is so unclear that it requires a comment, then maybe it should be rewritten instead".
23+
Є хороше правило з приводу цього: "якщо код настільки не зрозумілий, що потребує коментарів, можливо його краще переписати".
2424

25-
### Recipe: factor out functions
25+
### Рецепт: виносьте код у функції
2626

27-
Sometimes it's beneficial to replace a code piece with a function, like here:
27+
Іноді має сенс замінити частину коду на функцію, наприклад:
2828

2929
```js
3030
function showPrimes(n) {
3131
nextPrime:
3232
for (let i = 2; i < n; i++) {
3333

3434
*!*
35-
// check if i is a prime number
35+
// перевірка чи є `i` простим числом
3636
for (let j = 2; j < i; j++) {
3737
if (i % j == 0) continue nextPrime;
3838
}
@@ -43,7 +43,7 @@ function showPrimes(n) {
4343
}
4444
```
4545

46-
The better variant, with a factored out function `isPrime`:
46+
Кращим варінтом було б помістити код в окрему функцію `isPrime`:
4747

4848

4949
```js
@@ -52,7 +52,7 @@ function showPrimes(n) {
5252
for (let i = 2; i < n; i++) {
5353
*!*if (!isPrime(i)) continue;*/!*
5454

55-
alert(i);
55+
alert(i);
5656
}
5757
}
5858

@@ -65,21 +65,21 @@ function isPrime(n) {
6565
}
6666
```
6767

68-
Now we can understand the code easily. The function itself becomes the comment. Such code is called *self-descriptive*.
68+
Тепер ми можемо легко зрозуміти код. Сама функція замінила нам коментар. Такий код називається *самоописним*.
6969

70-
### Recipe: create functions
70+
### Рецепт: створюйте функції
7171

72-
And if we have a long "code sheet" like this:
72+
І якщо ми маємо такий довгий фрагмент коду:
7373

7474
```js
75-
// here we add whiskey
75+
// тут ми додаємо віскі
7676
for(let i = 0; i < 10; i++) {
7777
let drop = getWhiskey();
7878
smell(drop);
7979
add(drop, glass);
8080
}
8181

82-
// here we add juice
82+
// тут ми додаємо сік
8383
for(let t = 0; t < 3; t++) {
8484
let tomato = getTomato();
8585
examine(tomato);
@@ -90,7 +90,7 @@ for(let t = 0; t < 3; t++) {
9090
// ...
9191
```
9292

93-
Then it might be a better variant to refactor it into functions like:
93+
Тоді кращим варінтом буде замінити його на окремі функції:
9494

9595
```js
9696
addWhiskey(glass);
@@ -111,70 +111,71 @@ function addJuice(container) {
111111
}
112112
```
113113

114-
Once again, functions themselves tell what's going on. There's nothing to comment. And also the code structure is better when split. It's clear what every function does, what it takes and what it returns.
114+
Знову ж таки, ім'я функцій самі описують, що в них відбувається. Немає потреби коментувати такий код. Також кращою є структура коду, коли він розподілений. Стає зрозумілим, що функція робить, що вона приймає і що повертає.
115115

116-
In reality, we can't totally avoid "explanatory" comments. There are complex algorithms. And there are smart "tweaks" for purposes of optimization. But generally we should try to keep the code simple and self-descriptive.
116+
Насправді, ми не можемо уникнути повністю "пояснювальних" коментарів. Є складні алгоритми. Також існують деякі "прийоми" для оптимізації. Проте, як правило, ми повинні намагатись залишати код простим та самоописним.
117117

118-
## Good comments
118+
## Хороші коментарі
119119

120-
So, explanatory comments are usually bad. Which comments are good?
120+
Тож, пояснювальні коментарі зазвичай погані. Які ж тоді хороші?
121121

122-
Describe the architecture
123-
: Provide a high-level overview of components, how they interact, what's the control flow in various situations... In short -- the bird's eye view of the code. There's a special language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) to build high-level architecture diagrams explaining the code. Definitely worth studying.
122+
Описуйте архітектуру
123+
: Додавайте опис компонентів висого рівня, як вони взаємодіють, який потік управління мають у різних обставинах... Якщо коротко - огляд коду з висоту пташиного польоту. Є спеціальна мова [UML](https://uk.wikipedia.org/wiki/Unified_Modeling_Language) для побудови діаграм високорівневої архітектури коду. Її однозначно варто вчити.
124124

125-
Document function parameters and usage
126-
: There's a special syntax [JSDoc](http://en.wikipedia.org/wiki/JSDoc) to document a function: usage, parameters, returned value.
125+
Документуйте параметри функції та її використання
126+
: Існує спеціальний синтаксис [JSDoc](https://uk.wikipedia.org/wiki/JSDoc) для документації функції: її використання, параметри, значення, що повертає.
127127

128-
For instance:
129-
```js
130-
/**
131-
* Returns x raised to the n-th power.
132-
*
133-
* @param {number} x The number to raise.
134-
* @param {number} n The power, must be a natural number.
135-
* @return {number} x raised to the n-th power.
136-
*/
137-
function pow(x, n) {
138-
...
139-
}
140-
```
128+
Наприклад:
129+
130+
```js
131+
/**
132+
* повертає x у n-й степені.
133+
*
134+
* @param {number} x число, що треба піднести до степеня.
135+
* @param {number} n cтепінь, повинно бути натуральним числом.
136+
* @return {number} x піднесене у n-нну степінь.
137+
*/
138+
function pow(x, n) {
139+
...
140+
}
141+
```
141142

142-
Such comments allow us to understand the purpose of the function and use it the right way without looking in its code.
143+
Такі коментарі дозволяють нам зрозуміти мету функції та використовувати її правильно без потреби зазирати у її код.
143144

144-
By the way, many editors like [WebStorm](https://www.jetbrains.com/webstorm/) can understand them as well and use them to provide autocomplete and some automatic code-checking.
145+
До речі, багато редакторів, наприклад [WebStorm](https://www.jetbrains.com/webstorm/) можуть їх розуміти та використовувати для автодоповнення і деякої автоматичної перевірки коду.
145146

146-
Also, there are tools like [JSDoc 3](https://github.com/jsdoc3/jsdoc) that can generate HTML-documentation from the comments. You can read more information about JSDoc at <http://usejsdoc.org/>.
147+
Також є інструменти, наприклад [JSDoc 3](https://github.com/jsdoc3/jsdoc), які можуть генерувати HTML-документацію з коментарів. Ви можете почитати більше про JSDoc тут: <http://usejsdoc.org/>.
147148

148-
Why is the task solved this way?
149-
: What's written is important. But what's *not* written may be even more important to understand what's going on. Why is the task solved exactly this way? The code gives no answer.
149+
Чому завдання було вирішено у такий спосіб?
150+
: Те, що написано є дуже важливим. Проте, те, що *не* написано може бути ще більш важливим, щоб зрозуміти, що саме відбувається. Чому завдання було вирішено саме у такий спосіб? Код не дає відповідь на це питання.
150151

151-
If there are many ways to solve the task, why this one? Especially when it's not the most obvious one.
152+
Якщо існує декілька способів вирішення завдання, чому саме цей? Особливо, якщо цей спосіб не самий очевидний.
152153

153-
Without such comments the following situation is possible:
154-
1. You (or your colleague) open the code written some time ago, and see that it's "suboptimal".
155-
2. You think: "How stupid I was then, and how much smarter I'm now", and rewrite using the "more obvious and correct" variant.
156-
3. ...The urge to rewrite was good. But in the process you see that the "more obvious" solution is actually lacking. You even dimly remember why, because you already tried it long ago. You revert to the correct variant, but the time was wasted.
154+
Без таких коментарів можлива наступна ситуація:
155+
1. Ви (або ваш колега) відкриває код, написаний колись раніше, і бачить, що він "неоптимальний".
156+
2. Ви думаєте: "Який я був недосвідчений, і наскільки розумнішим я став зараз", і переписуєте код використовуючи "більш очевидний і правильний" варіант.
157+
3. ...Бажання переписати код було хорошим. Але в процесі ви помічаєте, що "більш очевидне" рішення не є оптимальним. Ви навіть смутно пригадуєте чому воно так, тому що колись давно вже намаглись спробувати такий варіант. Ви вертаєте правильне рішення, проте час було витрачено даремно.
157158

158-
Comments that explain the solution are very important. They help to continue development the right way.
159+
Коментарі, які пояснюють рішення є дуже важливими. Вони допомагають продовжувати розробку правильним шляхом.
159160

160-
Any subtle features of the code? Where they are used?
161-
: If the code has anything subtle and counter-intuitive, it's definitely worth commenting.
161+
Чи є якісь тонкощі у коді? Де вони використовуються?
162+
: Якщо код має якісь тонкощі та неочевидні речі, його точно варто коментувати.
162163

163-
## Summary
164+
## Підсумки
164165

165-
An important sign of a good developer is comments: their presence and even their absence.
166+
Коментарі є важливою ознакою хорошого розробника: як їх наявність, так і їх відсутність.
166167

167-
Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.
168+
Хороші коментарі полегшують нам підтримку коду, вертатись до нього через деякий час та використовувати його більш ефективно.
168169

169-
**Comment this:**
170+
**Коментуйте наступне:**
170171

171-
- Overall architecture, high-level view.
172-
- Function usage.
173-
- Important solutions, especially when not immediately obvious.
172+
- Загальну архітектуру, опис "високого рівня".
173+
- Використання функцій.
174+
- Важливі рішення, особливо, якщо вони не є очевидним.
174175

175-
**Avoid comments:**
176+
**Уникайте коментарі:**
176177

177-
- That tell "how code works" and "what it does".
178-
- Put them in only if it's impossible to make the code so simple and self-descriptive that it doesn't require them.
178+
- Які описують, як код працює і що він робить.
179+
- Пишіть їх тільки у тому випадку, коли не має змоги написати простий та самоописний код, якому пояснення не потрібні.
179180

180-
Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format).
181+
Коментарі також використовуються інструментами для автоматичної генерації документації, наприклад JSDoc3 - вони читають їх та генерують HTML-документи (або документи у іншому форматі).

0 commit comments

Comments
 (0)