rspec/rules/S5261/rule.adoc

42 lines
1.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-01-27 13:42:22 +01:00
The dangling ``++else++`` problem appears when nested ``++if++``/``++else++`` statements are written without curly braces. In this case, ``++else++`` is associated with the nearest ``++if++`` but that is not always obvious and sometimes the indentation can also be misleading.
2020-06-30 12:50:28 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rules reports ``++else++`` statements that are difficult to understand, because they are inside nested ``++if++`` statements without curly braces.
2020-06-30 12:50:28 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
Adding curly braces can generally make the code clearer (see rule S121 ), and in this situation of dangling ``++else++``, it really clarifies the intention of the code.
2020-06-30 12:50:28 +02:00
=== Noncompliant code example
2020-06-30 12:50:28 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:50:28 +02:00
----
if (a)
if (b)
d++;
else // Noncompliant, is the "else" associated with "if(a)" or "if (b)"? (the answer is "if(b)")
e++;
----
=== Compliant solution
2020-06-30 12:50:28 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:50:28 +02:00
----
if (a) {
if (b) {
d++;
}
} else { // Compliant, there is no doubt the "else" is associated with "if(a)"
e++;
}
----
== Resources
2020-06-30 12:50:28 +02:00
* https://en.wikipedia.org/wiki/Dangling_else