Skip to content

Comments #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Feb 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 70 additions & 69 deletions 1-js/03-code-quality/03-comments/article.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
# Comments
# Коментарі

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

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

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

## Bad comments
## Погані коментарі

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

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

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

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".
Є хороше правило з приводу цього: "якщо код настільки не зрозумілий, що потребує коментарів, можливо його краще переписати".

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

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

```js
function showPrimes(n) {
nextPrime:
for (let i = 2; i < n; i++) {

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

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


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

alert(i);
alert(i);
}
}

Expand All @@ -65,21 +65,21 @@ function isPrime(n) {
}
```

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

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

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

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

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

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

```js
addWhiskey(glass);
Expand All @@ -111,70 +111,71 @@ function addJuice(container) {
}
```

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.
Знову ж таки, ім'я функцій самі описують, що в них відбувається. Немає потреби коментувати такий код. Також кращою є структура коду, коли він розподілений. Стає зрозумілим, що функція робить, що вона приймає і що повертає.

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.
Насправді, ми не можемо уникнути повністю "пояснювальних" коментарів. Є складні алгоритми. Також існують деякі "прийоми" для оптимізації. Проте, як правило, ми повинні намагатись залишати код простим та самоописним.

## Good comments
## Хороші коментарі

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

Describe the architecture
: 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.
Описуйте архітектуру
: Додавайте опис компонентів висого рівня, як вони взаємодіють, який потік управління мають у різних обставинах... Якщо коротко - огляд коду з висоту пташиного польоту. Є спеціальна мова [UML](https://uk.wikipedia.org/wiki/Unified_Modeling_Language) для побудови діаграм високорівневої архітектури коду. Її однозначно варто вчити.

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

For instance:
```js
/**
* Returns x raised to the n-th power.
*
* @param {number} x The number to raise.
* @param {number} n The power, must be a natural number.
* @return {number} x raised to the n-th power.
*/
function pow(x, n) {
...
}
```
Наприклад:

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove extra space.
It's better to add this one to English version as PR and this will be merged into Ukrainian if approved.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created separate PR javascript-tutorial/en.javascript.info#1780 for this in English version

```js
/**
* повертає x у n-й степені.
*
* @param {number} x число, що треба піднести до степеня.
* @param {number} n cтепінь, повинно бути натуральним числом.
* @return {number} x піднесене у n-нну степінь.
*/
function pow(x, n) {
...
}
```

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

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.
До речі, багато редакторів, наприклад [WebStorm](https://www.jetbrains.com/webstorm/) можуть їх розуміти та використовувати для автодоповнення і деякої автоматичної перевірки коду.

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/>.
Також є інструменти, наприклад [JSDoc 3](https://github.com/jsdoc3/jsdoc), які можуть генерувати HTML-документацію з коментарів. Ви можете почитати більше про JSDoc тут: <http://usejsdoc.org/>.

Why is the task solved this way?
: 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.
Чому завдання було вирішено у такий спосіб?
: Те, що написано є дуже важливим. Проте, те, що *не* написано може бути ще більш важливим, щоб зрозуміти, що саме відбувається. Чому завдання було вирішено саме у такий спосіб? Код не дає відповідь на це питання.

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

Without such comments the following situation is possible:
1. You (or your colleague) open the code written some time ago, and see that it's "suboptimal".
2. You think: "How stupid I was then, and how much smarter I'm now", and rewrite using the "more obvious and correct" variant.
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.
Без таких коментарів можлива наступна ситуація:
1. Ви (або ваш колега) відкриває код, написаний колись раніше, і бачить, що він "неоптимальний".
2. Ви думаєте: "Який я був недосвідчений, і наскільки розумнішим я став зараз", і переписуєте код використовуючи "більш очевидний і правильний" варіант.
3. ...Бажання переписати код було хорошим. Але в процесі ви помічаєте, що "більш очевидне" рішення не є оптимальним. Ви навіть смутно пригадуєте чому воно так, тому що колись давно вже намаглись спробувати такий варіант. Ви вертаєте правильне рішення, проте час було витрачено даремно.

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

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

## Summary
## Підсумки

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

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

**Comment this:**
**Коментуйте наступне:**

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

**Avoid comments:**
**Уникайте коментарі:**

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

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