Fred Tingaud d3cfe19d7e
Fix broken or dangerous backquotes
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-30 10:33:56 +01:00

85 lines
2.7 KiB
Plaintext

== Why is this an issue?
Both ``++if-else++`` chains and ``++switch++`` statements are used for conditional branching, but they differ in their syntax and the way they handle multiple conditions.
* In an ``++if-else++`` chain, each condition is checked in order, and only the block associated with the first true condition is executed. If no condition is true, the code inside the ``++else++`` block (if present) will be executed.
* In a ``++switch++`` statement, the expression is evaluated once, and its value is compared against each case. If a matching case is found, the corresponding block of code is executed. The ``++break++`` statement is used to exit the ``++switch++`` block after a match. If no case matches the expression, the code inside the ``++default++`` block (if present) will be executed.
Having the same condition in both ``++if-else++`` chains and ``++switch++`` cases can lead to unreachable code and a potential source of bugs. It defeats the purpose of conditional branching and can make the code harder to read and maintain.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
if (event === 1) {
openWindow();
} else if (event === 2) {
closeWindow();
} else if (event === 1) { // Noncompliant: Duplicated condition 'event === 1'
moveWindowToTheBackground();
}
switch (event) {
case 1:
openWindow();
break;
case 2:
closeWindow();
break;
case 1: // Noncompliant: Duplicated case '1'
moveWindowToTheBackground();
break;
}
----
Carefully review your conditions and ensure that they are not duplicated across the ``++if-else++`` chain or ``++switch++`` statement. Use distinct conditions and default blocks to cover all scenarios without redundant checks.
[source,javascript,diff-id=1,diff-type=compliant]
----
if (event === 1) {
openWindow();
} else if (event === 2) {
closeWindow();
} else if (event === 3) {
moveWindowToTheBackground();
}
switch (event) {
case 1:
openWindow();
break;
case 2:
closeWindow();
break;
case 3:
moveWindowToTheBackground();
break;
}
----
== Resources
=== Documentation
* MDN web docs - link:++https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else++[``++if...else++``]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch[``++switch++``]
* Wikipedia - https://en.wikipedia.org/wiki/Unreachable_code[Unreachable code]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
This branch duplicates the one on line n.
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]