rspec/rules/S2583/python/rule.adoc

87 lines
2.4 KiB
Plaintext
Raw Normal View History

Conditional expressions which are always `true` or `false` can lead to https://en.wikipedia.org/wiki/Unreachable_code[unreachable code].
To fix this issue, either update the condition or remove the unreachable code.
== Why is this an issue?
Unreachable code is never executed, so it has no effect on the behaviour of the program.
If it is not executed because it no longer serves a purpose, then it adds unnecessary complexity.
Otherwise, it indicates that there is a logical error in the condition.
=== What is the potential impact?
Unreachable code affects maintainability.
It is harder for programmers to read, understand and modify the code when some parts are unreachable.
If the code should be reachable instead, then the program may not always behave as intended.
=== Exceptions
This rule will not raise an issue when
* The condition to reach the dead code is a boolean literal.
* The unreachable code is a simple statement, such as `pass`.
== How to fix it
You should first decide whether the unreachable code is useful.
If it is, then you should understand why the condition that leads to it is always false, and correct logical errors.
Otherwise, the code should be removed along with the condition.
=== Code examples
2020-06-30 12:48:07 +02:00
==== Noncompliant code example
2020-06-30 12:48:07 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2020-06-30 12:48:07 +02:00
----
def foo(a, b):
flag = True
2020-06-30 12:48:07 +02:00
if (a and not a): # Noncompliant
doSomething() # Never executed
2020-06-30 12:48:07 +02:00
if (flag): # Noncompliant
return "Result 1"
return "Result 2" # Never executed
2020-06-30 12:48:07 +02:00
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def foo(a, b):
if (a and not b):
doSomething()
return "Result 1"
----
=== How does this work?
The first condition is always false.
In this case, we decide that the call to `doSomething` is useful.
The problem is then a bug in the condition; for example, using `a` instead of `b`.
The second condition is always true.
Here, we decided that the second return statement is not useful anymore.
There may have been code manipulating the variable `flag` that was previously removed.
We can remove the unreachable code, the condition and the variable.
2020-06-30 12:48:07 +02:00
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[]