diff --git a/1-js/03-code-quality/04-ninja-code/article.md b/1-js/03-code-quality/04-ninja-code/article.md index 7846f6e21..6459dd6d4 100644 --- a/1-js/03-code-quality/04-ninja-code/article.md +++ b/1-js/03-code-quality/04-ninja-code/article.md @@ -1,185 +1,185 @@ -# Ninja code +# Código ninja -```quote author="Confucius" -Learning without thought is labor lost; thought without learning is perilous. +```quote author="Confucio" +Aprender sin pensar es inútil. Pensar sin aprender peligroso. ``` -Programmer ninjas of the past used these tricks to sharpen the mind of code maintainers. - -Code review gurus look for them in test tasks. +Los programadores ninjas del pasado usaron estos trucos para afilar la mente de los mantenedores de código. -Novice developers sometimes use them even better than programmer ninjas. +Los gurús de revisión de código los buscan en tareas de prueba. -Read them carefully and find out who you are -- a ninja, a novice, or maybe a code reviewer? +Los desarrolladores novatos algunas veces los usan incluso mejor que los programadores ninjas. +Léelos detenidamente y encuentra quién eres -- ¿un ninja?, ¿un novato?, o tal vez ¿un revisor de código? -```warn header="Irony detected" -Many try to follow ninja paths. Few succeed. +```warn header="Ironía detectada" +Muchos intentan seguir los caminos de los ninjas. Pocos tienen éxito. ``` -## Brevity is the soul of wit +## La brevedad es el alma del ingenio -Make the code as short as possible. Show how smart you are. +Haz el código lo más corto posible. Demuestra cuán inteligente eres. -Let subtle language features guide you. +Deja que las características sutiles del lenguaje te guíen. -For instance, take a look at this ternary operator `'?'`: +Por ejemplo, echa un vistazo a este operador ternario `'?'`: ```js -// taken from a well-known javascript library +// tomado de una librería de javascript muy conocida i = i ? i < 0 ? Math.max(0, len + i) : i : 0; ``` -Cool, right? If you write like that, a developer who comes across this line and tries to understand what is the value of `i` is going to have a merry time. Then come to you, seeking for an answer. +Fascinante, ¿cierto?. Si escribes de esa forma, un desarrollador que se encuentre esta línea e intente entender cuál es el valor de `i` la va a pasar muy mal. Por lo que tendrá que venir a ti, buscando una respuesta. -Tell them that shorter is always better. Initiate them into the paths of ninja. +Diles que mientras más corto mucho mejor. Guíalos a los caminos del ninja. -## One-letter variables +## Variables de una sola letra ```quote author="Laozi (Tao Te Ching)" -The Dao hides in wordlessness. Only the Dao is well begun and well -completed. +El Dao se esconde sin palabras. Solo el Dao está bien comenzado y bien +terminado. ``` -Another way to code faster is to use single-letter variable names everywhere. Like `a`, `b` or `c`. +Otra forma de programar más rápido es usando variables de una sola letra en todas partes. Como `a`, `b` o `c`. -A short variable disappears in the code like a real ninja in the forest. No one will be able to find it using "search" of the editor. And even if someone does, they won't be able to "decipher" what the name `a` or `b` means. +Una variable corta desaparece en el código como lo hace un ninja en un bosque. Nadie será capaz de encontrarla usando "buscar" en el editor. E incluso si alguien lo hace, no será capaz de "descifrar" el significado de `a` o `b`. -...But there's an exception. A real ninja will never use `i` as the counter in a `"for"` loop. Anywhere, but not here. Look around, there are many more exotic letters. For instance, `x` or `y`. +...Pero hay una excepción. Un verdadero ninja nunca usaría `i` como el contador en un bucle `"for"`. En cualquier otro lugar, pero no aquí. Mira alrededor, hay muchas más letras exóticas. Por ejemplo, `x` o `y`. -An exotic variable as a loop counter is especially cool if the loop body takes 1-2 pages (make it longer if you can). Then if someone looks deep inside the loop, they won't be able to quickly figure out that the variable named `x` is the loop counter. +Una variable exótica como el contador de un bucle es especialmente genial si el cuerpo del bucle toma 1-2 páginas (hazlo más grande si puedes). Entonces si alguien mira en las profundidades del bucle, no será capaz de figurar rápidamente que la variable llamada `x` es el contador del bucle. -## Use abbreviations +## Usa abreviaciones -If the team rules forbid the use of one-letter and vague names -- shorten them, make abbreviations. +Si las reglas del equipo prohíben el uso de nombres de una sola letra o nombres vagos -- acórtalos, haz abreviaciones. -Like this: +Como esto: - `list` -> `lst`. - `userAgent` -> `ua`. - `browser` -> `brsr`. - ...etc -Only the one with truly good intuition will be able to understand such names. Try to shorten everything. Only a worthy person should be able to uphold the development of your code. +Solo aquel con buena intuición será capaz de entender dichos nombres. Intenta acortar todo. Solo una persona digna debería ser capaz de sostener el desarrollo de tu código. -## Soar high. Be abstract. +## Vuela alto. Sé abstracto ```quote author="Laozi (Tao Te Ching)" -The great square is cornerless
-The great vessel is last complete,
-The great note is rarified sound,
-The great image has no form. +El gran cuadrado no tiene esquina
+La gran vasija se completa por última vez,
+La gran nota es un sonido enrarecido,
+La gran imagen no tiene forma. ``` -While choosing a name try to use the most abstract word. Like `obj`, `data`, `value`, `item`, `elem` and so on. +Cuando estés escogiendo un nombre intenta usar la palabra más abstracta. Como `obj`, `data`, `value`, `item`, `elem`, etc. -- **The ideal name for a variable is `data`.** Use it everywhere you can. Indeed, every variable holds *data*, right? +- **El nombre ideal para una variable es `data`.** Usalo lo más que puedas. En efecto, toda variable contiene *data*, ¿no? - ...But what to do if `data` is already taken? Try `value`, it's also universal. After all, a variable eventually gets a *value*. + ...¿Pero qué hacer si `data` ya está siendo usado? Intenta con `value`, también es universal. Después de todo, una variable eventualmente recibe un *value* (valor). -- **Name a variable by its type: `str`, `num`...** +- **Nombra una variable por su tipo: `str`, `num`...** - Give them a try. A young initiate may wonder -- are such names really useful for a ninja? Indeed, they are! + Pruébalos. Un recién iniciado puede preguntarse -- ¿Son estos nombres realmente útiles para un ninja? En efecto, ¡lo son! - Sure, the variable name still means something. It says what's inside the variable: a string, a number or something else. But when an outsider tries to understand the code, they'll be surprised to see that there's actually no information at all! And will ultimately fail to alter your well-thought code. + Claro, el nombre de la variable sigue significando algo. Dice que hay en el interior de la variable: una cadena de texto, un número o cualquier otra cosa. Pero cuando una persona ajena intenta entender el código, se verá sorprendido al ver que en realidad no hay información. Y finalmente fracasara en el intento de alterar tu código bien pensado. - The value type is easy to find out by debugging. But what's the meaning of the variable? Which string/number does it store? + El tipo de valor es fácil de encontrar con una depuración. Pero, ¿cuál es el significado de la variable? ¿Qué cadena de texto o número guarda? - There's just no way to figure out without a good meditation! + ¡No hay forma de saberlo sin una buena meditación! -- **...But what if there are no more such names?** Just add a number: `data1, item2, elem5`... +- **...Pero, ¿Y si ya no hay más de tales nombres?** Simplemente añade un número: `data1, item2, elem5`... -## Attention test +## Prueba de atención -Only a truly attentive programmer should be able to understand your code. But how to check that? +Solo un programador realmente atento debería ser capaz de entender tu código. Pero, ¿cómo comprobarlo? +`` -**One of the ways -- use similar variable names, like `date` and `data`.** +**Una de las maneras -- usa nombre de variables similares, como `date` y `data`.** -Mix them where you can. +Combínalos donde puedas. -A quick read of such code becomes impossible. And when there's a typo... Ummm... We're stuck for long, time to drink tea. +Una lectura rápida de dicho código se hace imposible. Y cuando hay un error de tipografía.... Ummm... Estamos atrapados por mucho tiempo, hora de tomar té. -## Smart synonyms +## Sinónimos inteligentes ```quote author="Confucius" -The hardest thing of all is to find a black cat in a dark room, especially if there is no cat. +Es difícil encontrar un gato negro en una habitación oscura, sobre todo cuando no está. ``` -Using *similar* names for *same* things makes life more interesting and shows your creativity to the public. +Usando nombres *similares* para las mismas cosas hace tu vida mas interesante y le muestra al público tu creatividad. -For instance, consider function prefixes. If a function shows a message on the screen -- start it with `display…`, like `displayMessage`. And then if another function shows on the screen something else, like a user name, start it with `show…` (like `showName`). +Por ejemplo, considera prefijos de funciones. Si una función muestra un mensaje en la pantalla -- comiénzalo con `mostrar...`, como `mostarMensaje`. Y entonces si otra función muestra en la pantalla otra cosa, como un nombre de usuario, comiénzalo con `presentar...` (como `presentarNombre`). -Insinuate that there's a subtle difference between such functions, while there is none. +Insinúa que hay una diferencia sutil entre dichas funciones, cuando no lo hay. -Make a pact with fellow ninjas of the team: if John starts "showing" functions with `display...` in his code, then Peter could use `render..`, and Ann -- `paint...`. Note how much more interesting and diverse the code became. +Has un pacto con tus compañeros ninjas del equipo: si John comienza funciones de "mostrar" con `presentar...` en su código, entonces Peter podría usar `exhibir..`, y Ann -- `pintar...`. Nota como el código es mucho más interesante y diverso ahora. -...And now the hat trick! +...¡Y ahora el truco del sombrero! -For two functions with important differences -- use the same prefix! +Para dos funciones con importantes diferencias -- ¡usa el mismo prefijo! -For instance, the function `printPage(page)` will use a printer. And the function `printText(text)` will put the text on-screen. Let an unfamiliar reader think well over similarly named function `printMessage`: "Where does it put the message? To a printer or on the screen?". To make it really shine, `printMessage(message)` should output it in the new window! +Por ejemplo, la función `imprimirPágina(página)` usara una impresora. Y la función `imprimirTexto(texto)` mostrará el texto en la pantalla.. Deja que un lector no familiar a tu código piense bien sobre una función llamada de forma similar `imprimirMensaje`: "¿Dónde coloca el mensaje? ¿A una impresora o en la pantalla?. Para que realmente se destaque, ¡`imprimirMensaje(mensaje)` debería mostrar el mensaje en una nueva ventana! -## Reuse names +## Reutilizar nombres ```quote author="Laozi (Tao Te Ching)" -Once the whole is divided, the parts
-need names.
-There are already enough names.
-One must know when to stop. +Una vez que el todo se divide, las partes
+necesitan nombres.
+Ya hay suficientes nombres.
+Uno debe saber cuándo parar. ``` -Add a new variable only when absolutely necessary. +Añade una nueva variable sólo cuando sea necesario. -Instead, reuse existing names. Just write new values into them. +En lugar, reutiliza nombres que ya existen. Simplemente escribe nuevo valores en ellos. -In a function try to use only variables passed as parameters. +En una función intenta sólo usar las variables pasadas como parámetros. -That would make it really hard to identify what's exactly in the variable *now*. And also where it comes from. The purpose is to develop the intuition and memory of a person reading the code. A person with weak intuition would have to analyze the code line-by-line and track the changes through every code branch. +Eso hará que sea realmente difícil identificar qué es exactamente la variable *ahora*. Y además de donde viene. El propósito es desarrollar la intuición y memoria de la persona que lee el código. Una persona con intuición débil tendrá que analizar el código línea por línea y seguir los cambios en cada rama de código. -**An advanced variant of the approach is to covertly (!) replace the value with something alike in the middle of a loop or a function.** +**Una variante avanzada del enfoque es reemplazar los valores de forma encubierta con algo parecido en la mitad de un bucle o una función.** -For instance: +Por ejemplo: ```js function ninjaFunction(elem) { - // 20 lines of code working with elem + // 20 líneas de código trabajando con elem elem = clone(elem); - // 20 more lines, now working with the clone of the elem! + // 20 líneas más, ¡ahora trabajando con el clon de elem! } ``` -A fellow programmer who wants to work with `elem` in the second half of the function will be surprised... Only during the debugging, after examining the code they will find out that they're working with a clone! +Un colega programador que quiera trabajar con `elem` en la segunda mitad de la función será sorprendido... ¡Solo durante la depuración, después de examinar el código encontrara que está trabajando con un clon! -Seen in code regularly. Deadly effective even against an experienced ninja. +Visto regularmente en códigos. Letalmente efectivo, incluso contra ninjas experimentados. -## Underscores for fun +## Guiones bajos por diversión -Put underscores `_` and `__` before variable names. Like `_name` or `__value`. It would be great if only you knew their meaning. Or, better, add them just for fun, without particular meaning at all. Or different meanings in different places. +Coloca guiones bajos `_` y `__` antes de los nombres de las variables. Como `_name` o `__value`. Sería genial si solo tú sabes su significado. O, mejor, añádelos simplemente por diversión, sin ningún significado especial. O diferentes significados en diferentes lugares. -You kill two rabbits with one shot. First, the code becomes longer and less readable, and the second, a fellow developer may spend a long time trying to figure out what the underscores mean. +Matarás dos pájaros de un solo tiro. Primero, el código se hará más largo y menos legible, y segundo, un colega desarrollador podría gastar una gran cantidad de tiempo intentado entender el significado del guion bajo. -A smart ninja puts underscores at one spot of code and evades them at other places. That makes the code even more fragile and increases the probability of future errors. +Un ninja inteligente coloca los guiones bajos en un solo lugar del código y los evita en otros lugars. Eso hace que el código sea mucho más frágil y aumenta la probabilidad de errores futuros. -## Show your love +## Muestra tu amor -Let everyone see how magnificent your entities are! Names like `superElement`, `megaFrame` and `niceItem` will definitely enlighten a reader. +¡Deja que todos vean cuán magníficas son tus entidades! Nombres como `superElement`, `megaFrame` and `niceItem` iluminaran sin duda al lector. -Indeed, from one hand, something is written: `super..`, `mega..`, `nice..` But from the other hand -- that brings no details. A reader may decide to look for a hidden meaning and meditate for an hour or two of their paid working time. +En efecto, por una parte, algo es escrito: `super..`, `mega..`, `nice..`, pero por otra parte -- no da ningún detalle. Un lector podría decidir mirar por un significado oculto y meditar por una hora o dos. -## Overlap outer variables +## Superpón variables externas ```quote author="Guan Yin Zi" -When in the light, can't see anything in the darkness.
-When in the darkness, can see everything in the light. +Cuando está a la luz, no puede ver nada en la oscuridad.
+Cuando está en la oscuridad, puede ver todo a la luz. ``` -Use same names for variables inside and outside a function. As simple. No efforts to invent new names. +Usa los mismos nombres para variables dentro y fuera de una función. Así de simple. Sin el esfuerzo de inventar nuevos nombres. ```js let *!*user*/!* = authenticateUser(); @@ -189,52 +189,49 @@ function render() { ... ...many lines... ... - ... // <-- a programmer wants to work with user here and... + ... // <-- un programador quiere trabajar con user aquí y... ... } ``` -A programmer who jumps inside the `render` will probably fail to notice that there's a local `user` shadowing the outer one. - -Then they'll try to work with `user` assuming that it's the external variable, the result of `authenticateUser()`... The trap is sprung! Hello, debugger... - +Un programador que se adentra en `render` probablemente no notara que hay un `user` local opacando al de afuera. -## Side-effects everywhere! +Entonces intentaran trabajar con `user` asumiendo que es la variable externa, el resultado de `authenticateUser()`... ¡Se activa la trampa! Hola, depurador... -There are functions that look like they don't change anything. Like `isReady()`, `checkPermission()`, `findTags()`... They are assumed to carry out calculations, find and return the data, without changing anything outside of them. In other words, without "side-effects". -**A really beautiful trick is to add a "useful" action to them, besides the main task.** +## ¡Efectos secundarios en todas partes! -An expression of dazed surprise on the face of your colleague when they see a function named `is..`, `check..` or `find...` changing something -- will definitely broaden your boundaries of reason. +Hay muchas funciones que parecen que no cambian nada. Como `estaListo()`, `comprobarPermiso()`, `encontrarEtiquetas()`... Se asume que sacan los cálculos, encuentran y regresan los datos, sin cambiar nada fuera de ellos. En otras palabras, sin "efectos secundarios". -**Another way to surprise is to return a non-standard result.** +**Un truco realmente bello es añadirles una acción "útil", además de su tarea principal.** -Show your original thinking! Let the call of `checkPermission` return not `true/false`, but a complex object with the results of the check. +Una expresión de sorpresa aturdida aparecerá en la cara de tus colegas cuando vean que la función llamada `es..`, `comprobar..` o `encontrar...` cambia algo -- definitivamente ampliará tus límites de razón. -Those developers who try to write `if (checkPermission(..))`, will wonder why it doesn't work. Tell them: "Read the docs!". And give this article. +**Otra forma de sorprender es retornar un resultado no estándar** +¡Muestra tu pensamiento original! Deja que la llamada de `comprobarPermiso` retorne no `true/false` sino un objeto complejo con los resultados de tu comprobación. -## Powerful functions! +## Funciones poderosas! ```quote author="Laozi (Tao Te Ching)" -The great Tao flows everywhere,
-both to the left and to the right. +El gran Tao fluye por todas partes,
+tanto a la izquierda como a la derecha. ``` -Don't limit the function by what's written in its name. Be broader. +No limites la función por lo que está escrito en el nombre. Se más abierto. -For instance, a function `validateEmail(email)` could (besides checking the email for correctness) show an error message and ask to re-enter the email. +Por ejemplo, una función `validarEmail(email)` podría (además de comprobar el email por exactitud) muestra un mensaje de error y preguntar de nuevo por el email. -Additional actions should not be obvious from the function name. A true ninja coder will make them not obvious from the code as well. +Acciones adicionales no deberían ser obvias por el nombre de la función. Un verdadero programador ninja no las hará obvias por el código tampoco. -**Joining several actions into one protects your code from reuse.** +**Uniendo muchas acciones en una proteje tu código de reusos.** -Imagine, another developer wants only to check the email, and not output any message. Your function `validateEmail(email)` that does both will not suit them. So they won't break your meditation by asking anything about it. +Imagina, otro desarrollador quiere solo comprobar el correo, y no mostrar ningún mensaje. Tu función `validarEmail(email)` que hace ambas no le será de utilidad. Así que no romperán tu meditación preguntando cualquier cosa sobre ello. -## Summary +## Resumen -All "pieces of advice" above are from the real code... Sometimes, written by experienced developers. Maybe even more experienced than you are ;) +Todos los *consejos* anteriores son de código real... Algunas veces, escrito por desarrolladores experimentados. Quizás incluso más experimentado que tú ;) -- Follow some of them, and your code will become full of surprises. -- Follow many of them, and your code will become truly yours, no one would want to change it. -- Follow all, and your code will become a valuable lesson for young developers looking for enlightenment. +- Sigue alguno de ellos, y tu código estará lleno de sorpresas. +- Sigue muchos de ellos, y tu código será realmente tuyo, nadie querrá cambiarlo. +- Sigue todos, y tu código será una lección valiosa para desarrolladores jóvenes buscando iluminación.