rspec/rules/S2232/java/rule.adoc
Marco Kaufmann 580f70f508
Modify rule S2232: reworked rule description for LayC format [SONARJAVA-4490] (#2580)
Co-authored-by: Dorian Burihabwa <75226315+dorian-burihabwa-sonarsource@users.noreply.github.com>
2023-07-21 17:42:23 +02:00

75 lines
2.3 KiB
Plaintext

== Why is this an issue?
There are several reasons to avoid using this method:
1. It is optionally available only for result sets of type `ResultSet.TYPE_FORWARD_ONLY`.
Database drivers will throw an exception if not supported.
2. The method can be expensive to execute as the database driver may need to fetch ahead one row to determine whether the current row is the last in the result set.
The documentation of the method explicitly mentions this fact.
3. What "the cursor is on the last row" means for an empty `ResultSet` is unclear.
Database drivers may return `true` or `false` in this case .
`ResultSet.next()` is a good alternative to `ResultSet.isLast()` as it does not have the mentioned issues.
It is always supported and, as per specification, returns `false` for empty result sets.
== How to fix it
Refactor your code to use `ResultSet.next()` instead of `ResultSet.isLast()`.
Be cautious of its different semantics and side effects on cursor positioning in the result set.
Verify that your program logic is still valid under these side effects and otherwise adjust it.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
ResultSet results = stmt.executeQuery("SELECT name, address FROM PERSON");
StringBuilder sb = new StringBuilder();
while (results.next() && !results.isLast()) { // Noncompliant
sb.append(results.getString("name") + ", ");
}
sb.append(results.getString("name"));
String formattedNames = sb.toString();
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
ResultSet results = stmt.executeQuery("SELECT name, address FROM PERSON");
List<String> names = new ArrayList<>();
while (results.next()) { // Compliant, and program logic refactored
names.add(results.getString("name"));
}
String formattedNames = names.stream().collect(Collectors.joining(", "));
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html#isLast--[Java SE 8 API Specification: ResultSet.isLast()]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this call to "isLast()".
'''
== Comments And Links
(visible only on this page)
=== on 24 Nov 2014, 19:15:41 Nicolas Peru wrote:
No message.
Otherwise seems ok.
endif::env-github,rspecator-view[]