diff --git a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md index 764e36c63..d610eda3b 100644 --- a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md +++ b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md @@ -1,29 +1,29 @@ -You could note the following: +Poderia notar no seguinte: ```js no-beautify -function pow(x,n) // <- no space between arguments -{ // <- figure bracket on a separate line - let result=1; // <- no spaces before or after = - for(let i=0;i -Now let's discuss the rules and reasons for them in detail. +Agora, vamos discutir essas regras e os razões para elas em detalhe. ```warn header="Irony Detected" -Nothing is set in stone here. These are style preferences, not religious dogmas. +Nada está gravado em pedra aqui. Estas são preferências de estilo, não rígidos dogmas. ``` -### Curly Braces +### Chavetas -In most JavaScript projects curly braces are written in "Egyptian" style with the opening brace on the same line as the corresponding keyword -- not on a new line. There should also be a space before the opening bracket, like this: +Em muitos projetos em JavaScript, chavetas são escritas no estilo "Egípcio", com a de abertura na mesma linha que a palavra-chave correspondente -- não numa nova linha. Também deveria existir um espaço antes da chaveta de abertura, desta forma: ```js if (condition) { - // do this - // ...and that - // ...and that + // faça isto + // ...e isso + // ...e aquilo } ``` -A single-line construct is an important edge case. Should we use brackets at all? If yes, then where? +Uma única linha de construção é um importante caso de exceção. Devemos utilizar chavetas, ou não? Se sim, então onde? -Here are the annotated variants so you can judge their readability for yourself: +Aqui estão variantes com anotações, para que por si mesmo julgue a sua legíbilidade: ![](figure-bracket-style.png) -In summary: -- For very short code, one line is acceptable. For example: `if (cond) return null`. -- But a separate line for each statement in brackets is usually easier to read. +Em resumo: +- Para código muito curto, uma única linha é aceitável. Por exemplo: `if (cond) return null`. +- Mas, uma linha em separado para cada instrução entre chavetas, geralmente é mais fácil de se ler. -### Line Length +### Comprimento da linha -No one likes to read a long horizontal line of code. It's best practice to split them up and limit the length of your lines. +Ninguém gosta de ler uma longa linha horizontal de código. A melhor prática é particioná-la e limitar o comprimento de cada linha. -The maximum line length should be agreed upon at the team-level. It's usually 80 or 120 characters. +O comprimento máximo de linha deveria ser acordado ao nível da equipa de trabalho. Geralmente, é de 80 ou 120 carateres. -### Indents +### Indentação -There are two types of indents: +Existem dois tipos de indentação: -- **Horizontal indents: 2 or 4 spaces.** +- **Indentação horizontal: 2 ou 4 espaços.** - A horizontal indentation is made using either 2 or 4 spaces or the "Tab" symbol. Which one to choose is an old holy war. Spaces are more common nowadays. + Uma indentação horizontal é feita quer inserindo 2 ou 4 espaços, ou empregando a tecla (*símbolo*) "Tab". Qual escolher, vem sendo uma guerra antiga. Hoje em dia, espaços são mais comuns. - One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the "Tab" symbol. + Uma vantagem de espaços sobre *tabs*, é que espaços permitem mais flexibilidade para personalizar a indentação do que o símbolo "Tab". - For instance, we can align the arguments with the opening bracket, like this: + Por exemplo, podemos alinhar os argumentos e a chaveta de abertura, desta forma: ```js no-beautify show(parameters, - aligned, // 5 spaces padding at the left + aligned, // 5 espaços adicionados à esquerda one, after, another @@ -105,9 +105,9 @@ There are two types of indents: } ``` -- **Vertical indents: empty lines for splitting code into logical blocks.** +- **Indentação vertical: linhas em branco para separar o código em blocos lógicos.** - Even a single function can often be divided into logical blocks. In the example below, the initialization of variables, the main loop and returning the result are split vertically: + Até uma simples função pode, por vezes, ser dividida em blocos lógicos. No exemplo abaixo, a inicialização de variáveis, o laço principal e o resultado retornado estão separados verticalmente: ```js function pow(x, n) { @@ -121,51 +121,51 @@ There are two types of indents: } ``` - Insert an extra newline where it helps to make the code more readable. There should not be more than nine lines of code without a vertical indentation. + Insira uma nova linha extra onde ajudar a tornar o código mais legível. Não deveriam existir mais de nove linhas de código sem uma indentação vertical. -### Semicolons +### Pontos-e-vírgula -A semicolon should be present after each statement, even if it could possibly be skipped. +Um ponto-e-vírgula deveria estar presente no fim de cada instrução, mesmo que possívelmente pudesse ser omitido. -There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors. +Existem linguagens em que o ponto-e-vírgula é verdadeiramente opcional, e raramente utilizado. Contudo, em JavaScript, há casos em que uma quebra-de-linha não é interpretada como um ponto-e-vírgula, deixando o código vulnerável a erros. -As you become more mature as a programmer, you may choose a no-semicolon style like [StandardJS](https://standardjs.com/). Until then, it's best to use semicolons to avoid possible pitfalls. +Há medida que ganhar maturidade como programador, poderá ser que escolha um estilo sem ponto-e-vírgula como [StandardJS](https://standardjs.com/). Até lá, o melhor será utilizar pontos-e-vírgula para evitar possíveis precalços. -### Nesting Levels +### Níveis aninhados -Try to avoid nesting code too many levels deep. +Tente evitar aninhar (*nesting*) código a muitos níveis de profundidade. -Sometimes it's a good idea to use the ["continue"](info:while-for#continue) directive in a loop to avoid extra nesting. +Por vezes, é boa ideia utilizar a diretiva ["continue"](info:while-for#continue) num laço, afim de evitar mais aninhamentos. -For example, instead of adding a nested `if` conditional like this: +Por exemplo, em vez de adicionar uma condição `if` aninhada (*nested*) desta forma: ```js for (let i = 0; i < 10; i++) { if (cond) { - ... // <- one more nesting level + ... // <- mais um nível de aninhamento } } ``` -We can write: +Poderá escrever: ```js for (let i = 0; i < 10; i++) { if (!cond) *!*continue*/!*; - ... // <- no extra nesting level + ... // <- nenhum nível de aninhamento extra } ``` -A similar thing can be done with `if/else` and `return`. +O mesmo poderá ser feito com `if/else` e `return`. -For example, two constructs below are identical. +Por exemplo, as duas construções abaixo são idênticas. -Option 1: +Opção 1: ```js function pow(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("'n' negativo não suportado"); } else { let result = 1; @@ -178,12 +178,12 @@ function pow(x, n) { } ``` -Option 2: +Opção 2: ```js function pow(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("'n' negativo não suportado"); return; } @@ -197,16 +197,16 @@ function pow(x, n) { } ``` -The second one is more readable because the "edge case" of `n < 0` is handled early on. Once the check is done we can move on to the "main" code flow without the need for additional nesting. +A segunda é mais legível, porque o "caso limite" (*edge case*) de `n < 0` é tratado cedo. Uma vez a verificação feita, podemos prosseguir para o fluxo "principal" do código, sem necessidade de aninhamento (*nesting*) adicional. -## Function Placement +## Localização da função -If you are writing several "helper" functions and the code that uses them, there are three ways to organize the functions. +Se estiver a escrever várias funções "auxiliares" (*"helper" functions*) acompanhadas do código que as utilizem, existem três formas para organizar as funções. -1. Functions declared above the code that uses them: +1. Funções acima do código que as utiliza: ```js - // *!*function declarations*/!* + // *!*declarações de funções*/!* function createElement() { ... } @@ -219,20 +219,20 @@ If you are writing several "helper" functions and the code that uses them, there ... } - // *!*the code which uses them*/!* + // *!*o código que as utiliza*/!* let elem = createElement(); setHandler(elem); walkAround(); ``` -2. Code first, then functions +2. O código primeiro, depois as funções: ```js - // *!*the code which uses the functions*/!* + // *!*o código que utiliza as funções*/!* let elem = createElement(); setHandler(elem); walkAround(); - // --- *!*helper functions*/!* --- + // --- *!*funções auxiliares (*helper functions*)*/!* --- function createElement() { ... } @@ -245,54 +245,54 @@ If you are writing several "helper" functions and the code that uses them, there ... } ``` -3. Mixed: a function is declared where it's first used. +3. Mista: uma função é declarada onde for empregue pela primeir vez. -Most of time, the second variant is preferred. +A maior parte da vezes, a segunda variante é a preferida. -That's because when reading code, we first want to know *what it does*. If the code goes first, then it provides that information. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do. +Isto porque ao ler o código, queremos primeiro saber *o que faz*. Se o código estiver primeiro, então ele fornece essa informação. Aí, talvez nem precisemos de ler as funções, especialmente se os seus nomes descreverem o que na verdade fazem. -## Style Guides +## Guias de Estilo -A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, where to put line breaks, etc. A lot of minor things. +Um guia de estilo contém regras gerais sobre "como escrever" código, ex. que aspas utilizar, quantos espaços indentar, onde colocar quebras de linha, etc. Uma quantidade de aspetos menores. -When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it. +Quando todos os membros de uma equipa usam o mesmo guia de estilo, o código parece uniforme, qualquer que seja o membro da equipa que o tenha escrito. -Of course, a team can always write their own style guide. Most of the time though, there's no need to. There are many existing tried and true options to choose from, so adopting one of these is usually your best bet. +Óbviamente, que uma equipa pode sempre escrever o seu próprio guia de estilo. Contudo, a maior parte das vezes não há necessidade. Existem muitas opções testadas e juramentadas por onde escolher, por isso adotar uma delas geralmente será a sua melhor aposta. -Some popular choices: +Algumas escolhas populares: - [Google JavaScript Style Guide](https://google.github.io/styleguide/javascriptguide.xml) - [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) - [Idiomatic.JS](https://github.com/rwaldron/idiomatic.js) - [StandardJS](https://standardjs.com/) -- (plus many more) +- (e muitas mais) -If you're a novice developer, start with the cheatsheet at the beginning of this chapter. Once you've mastered that you can browse other style guides to pick up common principles and decide which one you like best. +Se for um programador iniciante, começe pela cábula (*cheatsheet*) dísponivel no início deste capítulo. Dominando aquela, poderá procurar por outros guias de estilo afim de colher princípios gerais e decidir qual prefere. -## Automated Linters +## *Linters* Automatizados -Linters are tools that can automatically check the style of your code and make suggestions for refactoring. +*Linters*, são ferramentas que automáticamente verificam o estilo do seu código e fazem sugestões para o alterar. -The great thing about them is that style-checking can also find some bugs, like typos in variable or function names. Because of this feature, installing a linter is recommended even if you don't want to stick to one particular "code style". +O seu ponto-forte reside em, à medida que verificam o estilo, poderem encontrar alguns erros (*bugs*), como nomes de variáveis ou de funções mal-escritos. Devido a esta capacidade, é recomendado que instale um *linter* mesmo que não queira aderir a um "estilo de código" em particular. -Here are the most well-known linting tools: +Aqui estão as mais conhcidas ferramentas de *linting*: -- [JSLint](http://www.jslint.com/) -- one of the first linters. -- [JSHint](http://www.jshint.com/) -- more settings than JSLint. -- [ESLint](http://eslint.org/) -- probably the newest one. +- [JSLint](http://www.jslint.com/) -- um dos primeiros *linters*. +- [JSHint](http://www.jshint.com/) -- mais configurações do que *JSLint*. +- [ESLint](http://eslint.org/) -- provávelmente o mais recente. -All of them can do the job. The author uses [ESLint](http://eslint.org/). +Todos eles podem executar a tarefa. O autor utiliza [ESLint](http://eslint.org/). -Most linters are integrated with many popular editors: just enable the plugin in the editor and configure the style. +A maioria dos *linters* está integrada em muitos editores populares: apenas ative a extensão (*plugin*) no editor e configure o estilo. -For instance, for ESLint you should do the following: +Por exemplo, para o *ESLint* deveria efetuar o seguinte: -1. Install [Node.js](https://nodejs.org/). -2. Install ESLint with the command `npm install -g eslint` (npm is a JavaScript package installer). -3. Create a config file named `.eslintrc` in the root of your JavaScript project (in the folder that contains all your files). -4. Install/enable the plugin for your editor that integrates with ESLint. The majority of editors have one. +1. Instalar o [Node.js](https://nodejs.org/). +2. Instalar o *ESLint* com o comando `npm install -g eslint` (*npm* é um instalador de pacotes [*package installer*] para JavaScript). +3. Criar um ficheiro de configuração (*config file*) com o nome `.eslintrc` na raiz do seu projeto em JavaScript (na pasta que contém todos os seus ficheiros). +4. Instalar/ativar a extensão (*plugin*) no seu editor que faça a integração com o *ESLint*. A maior parte dos editores tem uma. -Here's an example of an `.eslintrc` file: +Aqui está um exemplo do ficheiro `.eslintrc`: ```js { @@ -309,16 +309,16 @@ Here's an example of an `.eslintrc` file: } ``` -Here the directive `"extends"` denotes that the configuration is based on the "eslint:recommended" set of settings. After that, we specify our own. +Aqui a diretiva `"extends"` denota que a configuração está baseada no conjunto de configurações em "eslint:recommended". A seguir, podemos especificar as nossas próprias. -It is also possible to download style rule sets from the web and extend them instead. See for more details about installation. +Também é possível descarregar conjuntos de regras de estilo da web e estendê-las. Veja em mais detalhes sobre a sua instalação. -Also certain IDEs have built-in linting, which is convenient but not as customizable as ESLint. +De igual modo, certos *IDEs* (Ambientes de Desenvolvimento Integrado) têm *linting* incorporado (*built-in*), o que é conveniente mas não tão personalizável como pelo *ESLint*. -## Summary +## Sumário -All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code, but all of them are debatable. +Todas as regras sintáticas descritas neste capítulo (e nos guias de estilo referenciados) têm como objetivo aumentar a legibilidade do seu código, mas todas são discutíveis. -When we think about writing "better" code, the questions we should ask are, "What makes the code more readable and easier to understand?" and "What can help us avoid errors?" These are the main things to keep in mind when choosing and debating code styles. +Quando pensarmos em escrever "melhor" código, as questões que deveríamos perguntar são, "O que faz o código mais legível e mais fácil de compreender?" e "O que nos pode ajudar a evitar erros?" Estes são os principais aspetos a ter em mente ao escolher e debater estilos de código. -Reading popular style guides will allow you to keep up to date with the latest ideas about code style trends and best practices. +A leitura de guias de estilo populares permite-nos estar a par das mais recentes ideias sobre tendências, e melhores práticas, de estilos de código.