rspec/rules/S2178/vbnet/rule.adoc

60 lines
2.3 KiB
Plaintext

== 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 evaluate the second argument of the operator if it is not needed to determine the result of the operation.
VB.NET provides logical operators that implement short-circuiting evaluations `AndAlso` and `OrElse`, as well as the non-short-circuiting versions `And` and `Or`. Unlike short-circuiting operators, the non-short-circuiting operators evaluate both operands and afterward perform the logical operation.
For example `False AndAlso FunctionCall` always results in `False` even when the `FunctionCall` invocation would raise an exception. In contrast, `False And FunctionCall` also evaluates `FunctionCall`, and results in an exception if `FunctionCall` raises an exception.
Similarly, `True OrElse 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,vbnet,diff-id=1,diff-type=noncompliant]
----
If GetTrue() Or GetFalse() Then ' Noncompliant: both sides evaluated
End If
----
==== Compliant solution
[source,vbnet,diff-id=1,diff-type=compliant]
----
If GetTrue() OrElse GetFalse() Then ' Compliant: short-circuit logic used
End If
----
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/logical-and-bitwise-operators[Logical and Bitwise Operators in Visual Basic]
* https://en.wikipedia.org/wiki/Short-circuit_evaluation[Short-circuit evaluation]
* https://en.wikipedia.org/wiki/Logical_connective[Boolean operators]
=== Articles & blog posts
* https://ericlippert.com/2015/11/02/when-would-you-use-on-a-bool/[Eric Lippert's blog - When would you use & on a bool?]
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[]