You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As we know from the chapter <info:structure>, comments can be single-line: starting with`//`and multiline: `/* ... */`.
3
+
Com sabem pel capítol <info:structure>, els comentaris poden ser d'una única línia: començant amb`//`o de múltiples línies: `/* ... */`.
4
4
5
-
We normally use them to describe how and why the code works.
5
+
Normalment els utilitzem per descriure com i perquè funciona el codi.
6
6
7
-
From the first sight, commenting might be obvious, but novices in programming usually get it wrong.
7
+
A primera vista, comentar pot semblar obvi, però els novells de la programació acostumen a equivocar-se.
8
8
9
-
## Bad comments
9
+
## Comentaris dolents
10
10
11
-
Novices tend to use comments to explain "what is going on in the code". Like this:
11
+
Els novells acostumen a utilitzar comentaris per explicar "que està passant en el codi". Per exemple:
12
12
13
13
```js
14
-
//This code will do this thing (...) and that thing (...)
15
-
// ...and who knows what else...
14
+
//Aquest codi farà això (...) i això (...)
15
+
// ...i qui sap que més...
16
16
very;
17
17
complex;
18
18
code;
19
19
```
20
20
21
-
But in good code the amount of such "explanatory" comments should be minimal. Seriously, code should be easy to understand without them.
21
+
Però en bon codi, la quantitat de comentaris "explicatius" hauria de ser mínima. De debò, el codi hauria de ser fàcil d'entendre sense comentaris.
22
22
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
+
Existeix una gran norma sobre això: "si el codi és tan poc clar que necessita un comentari, llavors potser hauria de ser reescrit en comptes".
24
24
25
-
### Recipe: factor out functions
25
+
### Recepta: funcions externes
26
26
27
-
Sometimes it's beneficial to replace a code piece with a function, like here:
27
+
De vegades és millor substituir un tros de codi amb una funció: així:
28
28
29
29
```js
30
30
functionshowPrimes(n) {
31
31
nextPrime:
32
32
for (let i =2; i < n; i++) {
33
33
34
34
*!*
35
-
//check if i is a prime number
35
+
//comprova si i és un nombre primer
36
36
for (let j =2; j < i; j++) {
37
37
if (i % j ==0) continue nextPrime;
38
38
}
@@ -43,8 +43,7 @@ function showPrimes(n) {
43
43
}
44
44
```
45
45
46
-
The better variant, with a factored out function `isPrime`:
47
-
46
+
La millor versió, amb una funció externa `isPrime`:
48
47
49
48
```js
50
49
functionshowPrimes(n) {
@@ -65,21 +64,21 @@ function isPrime(n) {
65
64
}
66
65
```
67
66
68
-
Now we can understand the code easily. The function itself becomes the comment. Such code is called *self-descriptive*.
67
+
Ara podem entendre el codi fàcilment. La funció mateixa es transforma en el comentari. Aquest tipus de codi s'anomena "auto descriptiu".
69
68
70
-
### Recipe: create functions
69
+
### Recepta: crea funcions
71
70
72
-
And if we have a long "code sheet" like this:
71
+
I si tenim una llarga "llista de codi" com aquesta:
73
72
74
73
```js
75
-
//here we add whiskey
74
+
//aquí afegim whisky
76
75
for(let i =0; i <10; i++) {
77
76
let drop =getWhiskey();
78
77
smell(drop);
79
78
add(drop, glass);
80
79
}
81
80
82
-
//here we add juice
81
+
//aquí afegim suc
83
82
for(let t =0; t <3; t++) {
84
83
let tomato =getTomato();
85
84
examine(tomato);
@@ -90,7 +89,7 @@ for(let t = 0; t < 3; t++) {
90
89
// ...
91
90
```
92
91
93
-
Then it might be a better variant to refactor it into functions like:
92
+
Llavors pot ser una millor variant si reescrivim en funcions com:
94
93
95
94
```js
96
95
addWhiskey(glass);
@@ -111,70 +110,70 @@ function addJuice(container) {
111
110
}
112
111
```
113
112
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.
113
+
De nou, les pròpies funcions ens expliquen el que està passant. No hi ha res a comentar. I també l'estructura del codi és millor quan la dividim. Queda clar el que fa cada funció, que rep i que retorna.
115
114
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.
115
+
En realitat, podem evitar totalment els comentaris "explicatius". Existeixen algoritmes complexos. Hi ha "trucs" intel·ligents amb motius d'optimització. Però generalment hauríem d'intentar mantenir el codi simple i auto explicatiu.
117
116
118
-
## Good comments
117
+
## Bons comentaris
119
118
120
-
So, explanatory comments are usually bad. Which comments are good?
119
+
Per tant, els comentaris explicatius solen ser dolents. Quins comentaris són bons?
121
120
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 diagram language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) for high-level architecture diagrams. Definitely worth studying.
121
+
Descriuen l'arquitectura:
122
+
: Proporcionen una visió general d'alt nivell dels components, com interactuen, quin és el flux de control en diferents situacions... En resum -- una vista d'ocell del codi. Hi ha un llenguatge de diagrames especial [UML](https://ca.wikipedia.org/wiki/Llenguatge_de_modelitzaci%C3%B3_unificat) per a diagrames d'arquitectura d'alt nivell. Sens dubte val la pena estudiar.
124
123
125
-
Document a function usage
126
-
: There's a special syntax [JSDoc](http://en.wikipedia.org/wiki/JSDoc)to document a function: usage, parameters, returned value.
124
+
Documenten l'ús d'una funció:
125
+
: Hi ha una sintaxi especial [JSDoc](http://en.wikipedia.org/wiki/JSDoc)per a documentar funcions: l'ús, els paràmetres i els valors retornats.
127
126
128
-
For instance:
127
+
Per exemple:
128
+
For instance:
129
129
```js
130
130
/**
131
-
* Returns x raised to the n-th power.
131
+
* Retorna x elevat a la potència de n.
132
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.
133
+
* @param {number} x El número a elevar.
134
+
* @param {number} n La potència, ha de ser un número natural.
135
+
* @return {number} x elevat a la potència de n.
136
136
*/
137
137
function pow(x, n) {
138
138
...
139
139
}
140
140
```
141
+
142
+
Aquest tipus de comentaris ens permeten entendre la finalitat de la funció i com utilitzar-la de la manera correcta sense mirar el codi.
143
+
Per cert, molts editors com [WebStorm](https://www.jetbrains.com/webstorm/) també els poden entendre i utilitzar-los per proveir auto complete i algun tipus de comprovació automàtica del codi.
144
+
145
+
També hi ha eines com [JSDoc 3](https://github.com/jsdoc3/jsdoc) que poden generar documentació en HTML a partir dels comentaris. Pots llegir més informació sobre JSDoc a <http://usejsdoc.org/>.
146
+
147
+
Per què el problema està resolt d'aquesta manera?
148
+
: El que està escrit és important. Però el que *no* està escrit pot ser inclòs més important per entendre el que està passant. Per què el problema està resolt d'aquesta manera específica? El codi no ens dóna cap resposta.
141
149
142
-
Such comments allow us to understand the purpose of the function and use it the right way without looking in its code.
143
-
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
-
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
-
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.
150
-
151
-
If there are many ways to solve the task, why this one? Especially when it's not the most obvious one.
152
-
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.
157
-
158
-
Comments that explain the solution are very important. They help to continue development the right way.
159
-
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.
150
+
Si hi han diferents maneres de resoldre el problema, per què aquesta? Especialment quan no és la més obvia.
151
+
152
+
Sense aquest tipus de comentaris la següent situació pot ocórrer:
153
+
1. Tu (o el teu company) obres el codi escrit ja fa un temps, i veus que és "sub-optim".
154
+
2. Penses: "Que ximple que vaig ser, i que intel·ligent que sóc ara", i reescrius el codi utilitzant la "manera més obvia i correcta".
155
+
3 ... El desig de reescriure era bo. Però durant el procés et dónes compte que la solució "més obvia" en realitat falla. Inclòs recordes vagament per què, perquè ja ho vas provar fa temps. Retornes a la variant correcta, però has perdut temps.
156
+
157
+
Els comentaris que ens expliquen la solució són molt importants. Ens ajuden a continuar el desenvolupament de manera correcta.
158
+
159
+
Hi ha algunes característiques subtils del codi? A on són utilitzades?
160
+
: Si el codi té alguna cosa subtil i contra intuïtiva, definitivament val la pena comentar-la.
162
161
163
-
## Summary
162
+
## Resum
164
163
165
-
An important sign of a good developer is comments: their presence and even their absence.
164
+
Un signe important d'un bon desenvolupador són els comentaris: la seva presència i fins i tot la seva absència.
166
165
167
-
Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.
166
+
Bons comentaris ens ajuden a mantenir el codi de manera correcta, tornar després d'un temps i utilitzar-lo de manera eficient.
168
167
169
-
**Comment this:**
168
+
**Comenta això:**
170
169
171
-
-Overall architecture, high-level view.
172
-
-Function usage.
173
-
-Important solutions, especially when not immediately obvious.
170
+
-Arquitectura en general, punts de vista d'alt nivell.
171
+
-Utilització de funcions.
172
+
-Solucions importants, especialment quan no són les immediatament obvies.
174
173
175
-
**Avoid comments:**
174
+
**Evita comentaris:**
176
175
177
-
-That tell "how code works" and "what it does".
178
-
-Put them only if it's impossible to make the code so simple and self-descriptive that it doesn't require those.
176
+
-Que ens expliquen "com funciona el codi" i "que és el que fa".
177
+
-Escriu-los només si és impossible fer que el codi sigui simple i auto descriptiu fins al punt que no els necessiti.
179
178
180
-
Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format).
179
+
Els comentaris també són utilitzats per eines de documentació automàtica com JSDoc3: els llegeixen i generen documents en HTML (o documents en altres formats).
0 commit comments