Angelo Buono c24d13b88a
Modify S1199: Migrate to LayC - Nested code blocks should not be used (#3233)
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-11 06:59:57 +00:00

83 lines
2.5 KiB
Plaintext

== Why is this an issue?
Nested code blocks can be used to create a new scope: variables declared within that block cannot be accessed from the outside,
and their lifetime end at the end of the block. However, this only happens when you use ES6 `let` or `const` keywords,
a class declaration or a function declaration (in strict mode). Otherwise, the nested block is redundant and should be removed.
=== Exceptions
The rule does not apply to the following cases:
* Block statements containing variable declarations using `let` or `const` keywords or class declarations are not redundant as they create a new scope.
[source,javascript]
----
{
let x = 1;
}
----
* The same applies to function declarations in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode[strict mode]
[source,javascript]
----
"use strict";
{
function foo() {}
}
----
* The rule also does not apply to the blocks that are part of the https://developer.mozilla.org/en-US/docs/Glossary/Control_flow[control flow].
[source,javascript]
----
if (condition) {
doSomething();
}
----
== How to fix it
The nested code blocks should be extracted into separate methods.
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
{ // Noncompliant: redundant code block
var foo = bar();
}
if (condition) {
doSomething();
{ // Noncompliant: redundant code block
doOtherStuff();
}
}
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
var foo = bar();
if (condition) {
doSomething();
doOtherStuff();
}
----
== Resources
=== Documentation
* Wikipedia - https://en.wikipedia.org/wiki/Single-responsibility_principle[Single Responsibility Principle]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block[block statement]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var[var]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let[let]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const[const]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class[class declaration]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function[function declaration]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode[strict mode]