rspec/rules/S2178/csharp/rule.adoc

51 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
https://en.wikipedia.org/wiki/Short-circuit_evaluation[Short-circuit evaluation] is an evaluation strategy for https://en.wikipedia.org/wiki/Logical_connective[Boolean operators], that doesn't evaluates the second argument of the operator if it is not needed to determine the result of the operation.
2020-06-30 12:48:07 +02:00
C# provides logical operators that implement short-circuit evaluation: `&&` and `||`, as well as non-short-circuit versions: `&` and `|`. Unlike short-circuit operators, non-short-circuit ones evaluate both operands and afterwards perform the logical operation.
2020-06-30 12:48:07 +02:00
For example `false && FunctionCall()` always results in `false`, even when `FunctionCall` invocation would raise an exception. Instead, `false & FunctionCall()` also evaluates `FunctionCall()`, and results in an exception if `FunctionCall()` invocation raises an exception.
Similarly, `true || FunctionCall()` always results in `true`, no matter what the return value of `FunctionCall()` would be.
The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances.
== How to fix it
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2020-06-30 12:48:07 +02:00
----
if (GetTrue() | GetFalse()) // Noncompliant: both sides evaluated
2020-06-30 12:48:07 +02:00
{
}
----
==== Compliant solution
2020-06-30 12:48:07 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2020-06-30 12:48:07 +02:00
----
if (GetTrue() || GetFalse()) // Compliant: short-circuit logic used
2020-06-30 12:48:07 +02:00
{
}
----
include::../resources-dotnet.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]