Note that there are some explanatory texts on larger screens.

plurals
  1. POAn Iterator which mutates and returns the same object. Bad practice?
    text
    copied!<p>I'm writing GC friendly code to read and return to the user a series of <code>byte[]</code> messages. Internally I reuse the same <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html" rel="nofollow noreferrer"><code>ByteBuffer</code></a> which means I'll repeatedly return the same <code>byte[]</code> instance <em>most of the time</em>. </p> <p>I'm considering writing cautionary javadoc and exposing this to the user as a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html" rel="nofollow noreferrer"><code>Iterator&lt;byte[]&gt;</code></a>. AFAIK it won't violate the <code>Iterator</code> contract, but the user certainly could be surprised if they do <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html#newArrayList%28java.util.Iterator%29" rel="nofollow noreferrer"><code>Lists.newArrayList(myIterator)</code></a> and get back a <code>List</code> populated with the same <code>byte[]</code> in each position!</p> <p>The question: is it <strong>bad practice</strong> for a class that <strong>may mutate and return the same object</strong> to implement the <code>Iterator</code> interface?</p> <ul> <li><p>If so, what is the best alternative? "Don't mutate/reuse your objects" is an easy answer. But it doesn't address the cases when reuse is very desirable.</p></li> <li><p>If not, how do you justify violating the <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment" rel="nofollow noreferrer">principle of least astonishment</a>?</p></li> </ul> <p>Two minor notes:</p> <ul> <li><p>I'm using Guava's <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/AbstractIterator.html" rel="nofollow noreferrer"><code>AbstractIterator</code></a> so remove() isn't really of concern.</p></li> <li><p>In my use case the user is <em>me</em> and the visibility of this class will be limited, but I've tried to ask this generally enough to apply more broadly.</p></li> </ul> <p><strong>Update:</strong> I'm accepting Louis' answer because it has 3x more votes than Keith's, but note that in my use case I'm planning to take the code that I left in a comment on Keith's answer to production.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload