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 4facc8b29..1f8678841 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,31 @@ -You could note the following: +Man kann Folgendes anmerken: ```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. +Nun lasst uns die Regeln ins Detail diskutieren. -```warn header="There are no \"you must\" rules" -Nothing is set in stone here. These are style preferences, not religious dogmas. +```warn header="Es gibt keine \"du musst\" Regeln" +Hier ist nichts in Stein gemeißelt. Diese sind nur Stilvorlieben, keine religiösen Vorschriften. ``` -### Curly Braces +### Geschweifte Klammern -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: +In den meisten JavaScript Projekten wird der "Egyptian"-Stil benutzt. Hierbei wird die geschweifte "Klammer auf" in derselben Zeile geschrieben wie der dazugehörige Schlüsselwort -- nicht in einer neuen Zeile. Vor der Klammer sollte auch ein Leerzeichen sein, so wie hier: ```js -if (condition) { - // do this - // ...and that - // ...and that +if (bedingung) { + // mach dies + // ...und das + // ...und das } ``` -A single-line construct, such as `if (condition) doSomething()`, is an important edge case. Should we use braces at all? +Ein Konstrukt aus einer einzigen Zeile wie `if (condition) doSomething()`, ist ein wichtiger Grenzfall. Sollten wir überhaupt geschweifte Klammern benutzen? -Here are the annotated variants so you can judge their readability for yourself: +Hier sind die kommentierten Varianten, sodass du die Lesbarkeit selbst beurteilen kannst: -1. 😠 Beginners sometimes do that. Bad! Curly braces are not needed: +1. 😠 Das machen die Anfänger manchmal. Schlecht! Geschweifte Klammern werden nicht benötigt: ```js - if (n < 0) *!*{*/!*alert(`Power ${n} is not supported`);*!*}*/!* + if (n < 0) *!*{*/!*alert(`Exponent ${n} wird nicht unterstützt`);*!*}*/!* ``` -2. 😠 Split to a separate line without braces. Never do that, easy to make an error when adding new lines: +2. 😠 Aufteilen auf zwei Zeilen ohne Klammern. Sollte niemals gemacht werden. Beim Hinzufügen neuer Zeilen können sehr schnell Fehler passieren: ```js if (n < 0) - alert(`Power ${n} is not supported`); + alert(`Exponent ${n} wird nicht unterstützt`); ``` -3. 😏 One line without braces - acceptable, if it's short: +3. 😏 Eine Zeile ohne Klammern - akzeptabel, wenn sie kurz ist: ```js - if (n < 0) alert(`Power ${n} is not supported`); + if (n < 0) alert(`Exponent ${n} wird nicht unterstützt`); ``` -4. 😃 The best variant: +4. 😃 Die beste Variante: ```js if (n < 0) { - alert(`Power ${n} is not supported`); + alert(`Exponent ${n} wird nicht unterstützt`); } ``` -For a very brief code, one line is allowed, e.g. `if (cond) return null`. But a code block (the last variant) is usually more readable. +Eine Zeile ist erlaubt, wenn es sich um eine kurze Codezeile handelt, z. B. `if (bedingung) return null`. Aber einen Codeblock (die letzte Variante), ist meistens besser lesbar. -### Line Length +### Zeilenlänge -No one likes to read a long horizontal line of code. It's best practice to split them. +Niemand liest gern lange, wagerechte Codezeilen. Die bewährte Vorgehensweise ist sie aufzuteilen. -For example: +Zum Beispiel: ```js -// backtick quotes ` allow to split the string into multiple lines +// Die Verwendung von Backticks ` erlauben uns die Aufteilung eines Strings auf mehrere Zeilen let str = ` - ECMA International's TC39 is a group of JavaScript developers, - implementers, academics, and more, collaborating with the community - to maintain and evolve the definition of JavaScript. + ECMA International's TC39 ist eine Gruppe von JavaScript Entwickler, + Implementierer, Akademiker, und mehr, die mit der Community zusammenarbeitet, + um die Definition von JavaScript aufrecht zu halten und weiterzuentwickeln. `; ``` -And, for `if` statements: +Und, für `if` -Anweisungen: ```js if ( @@ -104,23 +104,25 @@ if ( } ``` -The maximum line length should be agreed upon at the team-level. It's usually 80 or 120 characters. +Man sollte sich im Team auf eine maximale Zeilenlänge einigen. Sie beträgt normalerweise 80 oder 120 Zeichen. -### Indents +### Einrückungen -There are two types of indents: +Es gibt zwei Arten von Einrückungen: -- **Horizontal indents: 2 or 4 spaces.** +- **Waagerechte Einrückungen: 2 oder 4 Leerzeichen.** - A horizontal indentation is made using either 2 or 4 spaces or the horizontal tab symbol (key `key:Tab`). Which one to choose is an old holy war. Spaces are more common nowadays. + Eine waagerechte Einrückung besteht aus entweder 2 oder 4 Leerzeichen oder das waagerechte Tabsymbol (`key:Tab` Taste). Welches man benutzten soll ist eine alte Debatte. Leerzeichen werden heutzutage häufiger benutzt. - One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the tab symbol. + Ein Vorteil von Leerzeichen ist, dass sie eine flexiblere Benutzung von Einrückungen zulassen, als die Tab-Taste. + + + Zum Beispiel, können wir die Parametern untereinander, an dem "Klammer-auf-Symbol" ausrichten: - For instance, we can align the parameters with the opening bracket, like this: ```js no-beautify show(parameters, - aligned, // 5 spaces padding at the left + aligned, // 5 Leerzeichen links one, after, another @@ -129,9 +131,9 @@ There are two types of indents: } ``` -- **Vertical indents: empty lines for splitting code into logical blocks.** +- **Senkrechte Einrückungen: leere Zeilen um den Code in logisch zusammenhängende Blöcke zu unterteilen.** - 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: + Sogar eine einzige Methode kann in mehrere logische Blöcke unterteilt werden. In dem unten stehenden Beispiel werden die Initialisierung der Variable, die for-Schleife und das return-Statement durch leere Zeilen senkrecht voneinander getrennt. ```js function pow(x, n) { @@ -145,51 +147,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. + Füge eine leere Zeile dort hinzu, wo es hilft, die Lesbarkeit des Codes zu verbessern. Es sollten nicht mehr als neun Zeilen Code, ohne senkrechte Einrückung, geschrieben werden. -### Semicolons +### Semikolons -A semicolon should be present after each statement, even if it could possibly be skipped. +Ein Semikolon sollte nach jeder Anweisung gesetzt werden, auch wenn es nicht unbedingt notwendig ist. -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. See more about that in the chapter . +Es gibt Programiersprachen wo Semikonolns nicht zwingend erforderlich sind und deswegen kaum genutzt werden. In JavaScript gibt es aber Fälle, wo einen Zeilenumbruch nicht automatisch wie einen Semikolon interpretiert wird. Dadurch ist unser Code Fehleranfällig. Siehe mehr dazu in dem Kapitel . -If you're an experienced JavaScript programmer, you may choose a no-semicolon code style like [StandardJS](https://standardjs.com/). Otherwise, it's best to use semicolons to avoid possible pitfalls. The majority of developers put semicolons. +Wenn du ein Erfahrener JavaScript Programierer bist, kannst du einen "no-semicolon-style" wie [StandardJS](https://standardjs.com/) verwenden. Ansonsten ist es besser Semikolons zu benutzen, um mögliche Fallen zu vermeiden. Die meisten Entwickler benutzen Semikolons. -### Nesting Levels +### Verschachtelungsebenen -Try to avoid nesting code too many levels deep. +Versuche es zu vermeiden, Code auf zu viele Ebenen zu verschachteln. -For example, in the loop, it's sometimes a good idea to use the [`continue`](info:while-for#continue) directive to avoid extra nesting. +Zum Beispiel ist es in einer Schleife manchmal besser die [`continue`](info:while-for#continue) Anweisung zu verwenden, um weitere Verschachtelung zu vermeiden. -For example, instead of adding a nested `if` conditional like this: +Zum Beispiel: anstatt einer verschachtelten `if` Anweisung wie hier: ```js for (let i = 0; i < 10; i++) { if (cond) { - ... // <- one more nesting level + ... // <- eine weitere Verschachtelungsebene } } ``` -We can write: +Können wir lieber das machen: ```js for (let i = 0; i < 10; i++) { if (!cond) *!*continue*/!*; - ... // <- no extra nesting level + ... // <- keine Weitere Verschachtelungsebene } ``` -A similar thing can be done with `if/else` and `return`. +Änliches kann man mit `if/else` und `return` machen. -For example, two constructs below are identical. +Zum Beispiel: die zwei Konstrukte unten sind identisch. Option 1: ```js function pow(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("Negatives 'n' nicht unterstützt"); } else { let result = 1; @@ -207,7 +209,7 @@ Option 2: ```js function pow(x, n) { if (n < 0) { - alert("Negative 'n' not supported"); + alert("Negatives 'n' nicht unterstützt"); return; } @@ -221,16 +223,16 @@ function pow(x, n) { } ``` -The second one is more readable because the "special 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. +Die zweite Variante ist besser lesbar, denn der "Spezialfall" `n < 0` wird gleich am Anfang behandelt. Sobald die Überprüfung fertig ist, können wir mit dem "Hauptteil" des Codes weitermachen. -## Function Placement +## Methodenplatzierung -If you are writing several "helper" functions and the code that uses them, there are three ways to organize the functions. +Wenn du mehrere "Hilfsmethoden" schreibst und auch weiterer Code der diese Methoden benutzt, dann gibt es drei Möglichkeiten, diese Mehtoden zu gliedern. -1. Declare the functions *above* the code that uses them: +1. Methoden werden *über* dem Code deklariert, der sie benutzt: ```js - // *!*function declarations*/!* + // *!*Methodendeklarationen*/!* function createElement() { ... } @@ -243,20 +245,20 @@ If you are writing several "helper" functions and the code that uses them, there ... } - // *!*the code which uses them*/!* + // *!*der Code der die Methoden benutzt*/!* let elem = createElement(); setHandler(elem); walkAround(); ``` -2. Code first, then functions +2. Code zuerst, danach die Methoden ```js - // *!*the code which uses the functions*/!* + // *!*der Code der die Methoden benutzt*/!* let elem = createElement(); setHandler(elem); walkAround(); - // --- *!*helper functions*/!* --- + // --- *!*Hilfsmethoden*/!* --- function createElement() { ... } @@ -269,54 +271,56 @@ 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. Gemischt: eine Methode wird dort deklariert, wo sie zuerst benutzt wird. -Most of time, the second variant is preferred. +Meistens wird die zweite Variante bevorzugt. -That's because when reading code, we first want to know *what it does*. If the code goes first, then it becomes clear from the start. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do. +Das liegt daran, dass man beim Lesen von Code zuerst wissen möchte *was er tut*. Wenn der Code zuerst kommt, dann ist es von vornherein klar. Vor allem wenn die Namen der Methoden sehr aussagekräftig sind, kann es vielleicht sein, dass wir die Methoden gar nicht mehr lesen müssen. -## Style Guides +## Style Guides (Gestaltungsleitfaden) -A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, the maximal line length, etc. A lot of minor things. +Einen Gestaltungsleitfaden enthält allgemeine Regeln über die Art "wie man Code schreibt", z. B. welche Anfürungszeichen zu benutzen, wie viele Leerzeichen einzurücken, die maximale Zeilenlänge, etc. Sehr viele Kleinigkeiten. -When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it. +Wenn alle Teammitglieder denselben Leitfaden folgen, dann ist der Code einheitlich, egal von wem er geschrieben wurde. -Of course, a team can always write their own style guide, but usually there's no need to. There are many existing guides to choose from. +Natürlich kann ein Team ein eigenes Leitfaden aufstellen, aber normalerweise ist das nicht nötig. Es gibt schon viele die man benutzen kann. -Some popular choices: +Ein paar bekannte Beispiele: - [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html) - [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) - [Idiomatic.JS](https://github.com/rwaldron/idiomatic.js) - [StandardJS](https://standardjs.com/) -- (plus many more) +- (und viele andere) + +Wenn du ein Neuling bist, starte mit dem Spickzettel am Anfang dieses Kapitels. Danach kannst du dich in andere Style Guides einlesen um weitere Ideen zu sammeln und selbst entscheiden welches du am besten findest. -If you're a novice developer, start with the cheat sheet at the beginning of this chapter. Then you can browse other style guides to pick up more ideas and decide which one you like best. +## Automatische Linters -## Automated Linters +Linters sind Tools die automatisch die Gestaltung deines Codes prüfen und Verbesserungsvorschläge machen. -Linters are tools that can automatically check the style of your code and make improving suggestions. +Das großartige daran ist, beim Prüfen können sie auch Bugs finden, wie zum Beispiel Schreibfehler in Variablen- oder Methodennamen. Aus diesem Grund ist die Benutzung eines Linters empfohlen, auch wenn man sich nicht an einem bestimmten Leitfaden halten möchte. -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, using a linter is recommended even if you don't want to stick to one particular "code style". +Hier sind ein paar bekannte Beispiele: -Here are some well-known linting tools: -- [JSLint](https://www.jslint.com/) -- one of the first linters. -- [JSHint](https://jshint.com/) -- more settings than JSLint. -- [ESLint](https://eslint.org/) -- probably the newest one. +- [JSLint](http://www.jslint.com/) -- einer der ersten Linters. +- [JSHint](http://www.jshint.com/) -- mehr Einstellungen als JSLint. +- [ESLint](http://eslint.org/) -- wahrscheinlich das Neuste. -All of them can do the job. The author uses [ESLint](https://eslint.org/). +Alle erfüllen die Anforderungen. Der Autor benutzt [ESLint](http://eslint.org/). -Most linters are integrated with many popular editors: just enable the plugin in the editor and configure the style. -For instance, for ESLint you should do the following: +Die meisten Linters sind in vielen Editoren integriert. Man muss lediglich in dem Editor den Plugin aktivieren und den Stil konfigurieren. -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. +Zum Beispiel, für ESLint muss man Folgendes machen: -Here's an example of an `.eslintrc` file: +1. Installiere [Node.js](https://nodejs.org/). +2. Installiere ESLint mit dem Befehl `npm install -g eslint` (npm ist ein Befehl zum Installieren von Packages in JavaScript). +3. Erstelle eine Konfigurationsdatei `.eslintrc` in dem Root-Verzeichnis deines JavaScript Projekts (der Ordner der alle Dateien enthält). +4. Installiere/aktiviere den Plugin für dein Editor der ESLint integriert hat. Die Mehrheit haben ihn. + +Hier ist ein Beispiel einer `.eslintrc` Datei: ```js { @@ -333,16 +337,17 @@ 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. +Hier bedeutet die `"extends"`-Anweisung, dass die Konfiguration auf die "eslint:recommended" Einstellungen beruht. Danach geben wir unsere Einstellungen an. + +Es ist auch möglich einen "style rule set" aus dem Internet herunterzuladen und zu erweitern. Schaue dir an, für mehr Details über die Einrichtung. -It is also possible to download style rule sets from the web and extend them instead. See for more details about installation. -Also certain IDEs have built-in linting, which is convenient but not as customizable as ESLint. +Manche Entwicklungsumgebungen haben installierte Linters. Das ist zwar praktisch, aber sie sind nicht so anpassbar wie ESLint -## Summary +## Zusammenfassung -All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code. All of them are debatable. +Alle Syntaxregeln die in diesem Kapitel (und in den verlinkten Kapiteln) beschrieben wurden, haben das Ziel, die Lesbarkeit deines Codes zu verbessern. Sie sind alle umstritten. -When we think about writing "better" code, the questions we should ask ourselves 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. +Wenn wir über "besseren" Code nachdenken, sollten wir uns folgende Fragen stellen: "Wie machen wir unser Code besser lesbar und leichter zu verstehen?" und "Was hilft uns, Fehler zu vermeiden?" Das sind die wichtigsten Sachen die man im Hinterkopf behalten muss wenn man sich für einen Codestil entscheidet. -Reading popular style guides will allow you to keep up to date with the latest ideas about code style trends and best practices. +Das Lesen von bekannten Style Guides hilft uns auf den neusten Stand zu bleiben, was Trends und bewährte Vorgehensweisen angeht.