Indentation
When control statements (if
, while
etc.) are too long or exceed the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line. Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
Examples
⇣ Incorrect code for this rule:
if ((season === "winter" || snowflakes === 20) && aVeryLongMethodNameThatExceedsTheLineLength() && anotherLongNamedMethod()) {
snow();
}
if (snowflakes === 20 &&
season === "winter") {
snow();
}
if (snowflakes === 20
&& season === "winter") {
snow();
}
if (
snowflakes === 20 &&
season === "winter"
) {
snow();
}
⇡ Correct code for this rule:
if (snowflakes === 20 && season === "winter") {
snow();
}
if (
(snowflakes === 20 || season === "winter") &&
aVeryLongMethodNameThatExceedsTheLineLength() &&
anotherLongNamedMethod()
) {
snow();
}
if (snowflakes === 20 && season === "winter") {
snow();
}
Selection Operators
Prefer to use control statements instead of selection operators.
Examples
⇣ Incorrect code for this rule:
!hasSnow && buildSnowblocks();
⇡ Correct code for this rule:
if (!hasSnow) {
buildSnowblocks();
}