80 lines
2.1 KiB
Plaintext
80 lines
2.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
A chain of https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-if-statement[if/else if] statements is evaluated from top to bottom. At most, only one branch will be executed: the first statement with a condition that evaluates to `true`.
|
|
Therefore, duplicating a condition leads to unreachable code inside the duplicated condition block. Usually, this is due to a copy/paste error.
|
|
|
|
The result of such duplication can lead to unreachable code or even to unexpected behavior.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
if (param == 1)
|
|
{
|
|
OpenWindow();
|
|
}
|
|
else if (param == 2)
|
|
{
|
|
CloseWindow();
|
|
}
|
|
else if (param == 1) // Noncompliant: condition has already been checked
|
|
{
|
|
MoveWindowToTheBackground(); // unreachable code
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
if (param == 1)
|
|
{
|
|
OpenWindow();
|
|
}
|
|
else if (param == 2)
|
|
{
|
|
CloseWindow();
|
|
}
|
|
else if (param == 3)
|
|
{
|
|
MoveWindowToTheBackground();
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-if-statement[The if statement]
|
|
|
|
|
|
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)
|
|
|
|
=== on 25 Mar 2015, 16:03:23 Tamas Vajk wrote:
|
|
\[~ann.campbell.2] should I add the See section for C# as well?
|
|
|
|
=== on 25 Mar 2015, 16:24:48 Ann Campbell wrote:
|
|
\[~tamas.vajk] these language-specific subtasks override portions of their parent tasks, and the description field is treated as 5 separate parts: description, Noncompliant Code Example, Compliant Solution, Exceptions, and references (See). There's no need to copy/paste the references to this child ticket, but do include them in the implementation's rule description.
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|