I am writing an iterator that iterates over a list of lists by delegating to the “current” lists own iterator. (No I’m not, but this is a simple example). Now, when I reach the end of one list, I need to update the delegate to point to the next lists’ iterator. Can I do this in “hasNext”? Or is it better to implement in “next” prior to returning to the caller? I feel “hasNext” should better be side effect free. What’s your opinion on this?
Share
It would be OK for
hasNextto have side effects as long as they are not perceptible from the outside. Above all, it must be idempotent. It is in fact often the case thathasNextcan’t know whether there is a next without fetching it, and, even if it could “unfetch”, it is OK to cache.