rspec/rules/S2113/java/rule.adoc
2022-02-04 16:28:24 +00:00

43 lines
921 B
Plaintext

The ``++hasNext++`` method of an ``++Iterator++`` should only report on the state of the iterator, not change it. Making a change to an iterator in its ``++hasNext++`` method violates all expectations of what the method will do, and almost guarantees bad results when the iterator class is used.
== Noncompliant Code Example
[source,java]
----
public class MyItr implements Iterator<MyClass> {
//...
public boolean hasNext() {
if (next() != null) { // Noncompliant
return true;
}
return false;
}
----
== Compliant Solution
[source,java]
----
public class MyItr implements Iterator<MyClass> {
private List<MyClass> list;
private int index = 0;
//...
public boolean hasNext() {
return index < list.size();
}
----
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]