rspec/rules/S2272/java/rule.adoc
Dorian Burihabwa 083977aded
Modify rule S2272: LaYC review [SONARJAVA-4490] (#2592)
Reviewed for typos, and added a link to Javadoc.
2023-07-21 17:22:30 +02:00

54 lines
1.1 KiB
Plaintext

== Why is this an issue?
By contract, any implementation of the `java.util.Iterator.next()` method should throw a `NoSuchElementException` exception when the iteration has no more elements.
Any other behavior when the iteration is done could lead to unexpected behavior for users of this `Iterator`.
=== Noncompliant code example
[source,java,diff-id=1,type=noncompliant]
----
public class MyIterator implements Iterator<String> {
...
public String next() {
if (!hasNext()) {
return null;
}
// ...
}
}
----
=== Compliant solution
[source,java,diff-id=1,type=compliant]
----
public class MyIterator implements Iterator<String> {
...
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
// ...
}
}
----
== Resources
* https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--[JavaDoc 8 - java.util.Iterator]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Add a "NoSuchElementException" for iteration beyond the end of the collection.
endif::env-github,rspecator-view[]