Modify rule S1751: Update rule description according to the LaYC (#2881)

Co-authored-by: Marco Kaufmann <83189575+kaufco@users.noreply.github.com>
This commit is contained in:
Irina Batinic 2023-08-15 17:28:14 +02:00 committed by GitHub
parent ff2b22601a
commit e2dec3882d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,9 +1,82 @@
include::../rule.adoc[]
== Why is this an issue?
A loop with at most one iteration is equivalent to an `if` statement.
This can confuse developers and make the code less readable since loops are not meant to replace `if` statements.
If the intention was to conditionally execute the block only once, an `if` statement should be used instead.
Otherwise, the loop should be fixed so the loop block can be executed multiple times.
A loop statement with at most one iteration can happen when a statement that unconditionally transfers control,
such as a jump or throw statement, is misplaced inside the loop block.
This rule arises when the following statements are misplaced:
* `break`
* `return`
* `throw`
== How to fix it
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
int i = 0;
while(i < 10) { // Noncompliant; loop only executes once
System.out.println("i is " + i);
i++;
break;
}
----
[source,java,diff-id=2,diff-type=noncompliant]
----
for (int i = 0; i < 10; i++) { // Noncompliant; loop only executes once
if (i == x) {
break;
} else {
System.out.println("i is " + i);
return;
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
int i = 0;
while (i < 10) {
System.out.println("i is " + i);
i++;
}
----
[source,java,diff-id=2,diff-type=compliant]
----
for (int i = 0; i < 10; i++) {
if (i == x) {
break;
} else {
System.out.println("i is " + i);
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html[Oracle - The for Statement]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
@ -11,7 +84,9 @@ include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]