rspec/rules/S2589/python/rule.adoc
nicolas-gauthier-sonarsource ab6d0f08b7
Modify S2589: Migrate to LaYC (#3297)
## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
2023-10-18 14:26:59 +02:00

90 lines
2.1 KiB
Plaintext

include::../description-common.adoc[]
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
def f(b):
a = True
if a: # Noncompliant
do_something()
if a and b: # Noncompliant; "a" is always "True"
do_something_else()
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def f(b):
do_something()
if b:
do_something_else()
----
==== Noncompliant code example
[source,python,diff-id=2,diff-type=compliant]
----
def f(a, b):
if a is None and b is None:
do_something()
elif a is not None or b is not None: # Noncompliant
do_something_else()
----
==== Compliant solution
[source,python,diff-id=2,diff-type=noncompliant]
----
def f(a, b):
if a is None and b is None:
do_something()
else:
do_something_else()
----
=== How does this work?
In the first example, the gratuitous condition `a` is simply `True`.
Hence, the first `if`-statement can be removed, as `do_something()` is always
executed.
Additionally, the second `if`-statement can be simplified since the execution
of `do_something_else()` actually only depends on `b`.
In the second example, the condition on the `elif`-branch is gratuitous because
it is a logical consequence of a condition that already has been confirmed to
hold:
The condition of the `elif`-branch is only evaluated if the condition on the
`if`-branch evaluates to `False`.
If that condition is `False`, then as a consequence, at least one of `a` or `b`
is not `None`.
This is exactly the circumstance that is formalized by the second condition.
Thus it always evaluates to `True` when checked.
Therefore, the `elif`-branch can be simplified to an `else`-branch without a
condition.
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]