一个迭代并返回相同对象的迭代器。不好的做法? [英] An Iterator which mutates and returns the same object. Bad practice?

查看:105
本文介绍了一个迭代并返回相同对象的迭代器。不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写GC友好代码来读取并向用户返回一系列 byte [] 消息。在内部我重复使用相同的 ByteBuffer 这意味着我将在大多数情况下重复返回相同的 byte [] 实例

I'm writing GC friendly code to read and return to the user a series of byte[] messages. Internally I reuse the same ByteBuffer which means I'll repeatedly return the same byte[] instance most of the time.

我正在考虑编写警示javadoc并将其作为 Iterator< byte []> 。 AFAIK它不会违反 Iterator 合同,但如果用户 Lists.newArrayList(myIterator) 并在每个位置返回一个 List ,其中填入相同的 byte []

I'm considering writing cautionary javadoc and exposing this to the user as a Iterator<byte[]>. AFAIK it won't violate the Iterator contract, but the user certainly could be surprised if they do Lists.newArrayList(myIterator) and get back a List populated with the same byte[] in each position!

问题:对于可能会变异并返回相同对象的类来实现不良做法 Iterator interface?

The question: is it bad practice for a class that may mutate and return the same object to implement the Iterator interface?


  • 如果是这样,最佳选择是什么? 不要改变/重用你的对象是一个简单的答案。但它没有解决非常需要重用的情况。

  • 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.

如果没有,你如何证明违反最不惊讶的原则

If not, how do you justify violating the principle of least astonishment?

两个小注:

  • I'm using Guava's AbstractIterator so remove() isn't really of concern.

在我的用例中,用户是 me ,此类的可见性将受到限制,但我试图通常要求这个更广泛地适用。

In my use case the user is me and the visibility of this class will be limited, but I've tried to ask this generally enough to apply more broadly.

更新:我接受路易斯的答案,因为它的票数比基思多3倍,但请注意,在我的用例中,我打算把我留下的代码留给Keith的回答。 o生产。

Update: 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.

推荐答案

EnumMap 基本完成了这个 entrySet()迭代器,它导致今天令人困惑,疯狂,令人沮丧的错误。

EnumMap did essentially exactly this in its entrySet() iterator, which causes confusing, crazy, depressing bugs to this day.

如果我是你,我只是不会使用 Iterator - 我会写一个不同的API(可能与Iterator完全不同,甚至)并实现它。例如,您可以编写一个新的API,将输入 ByteBuffer 写入,以便将消息写入,因此API的用户可以控制是否或不是缓冲区被重用。这似乎相当直观(用户可以编写明显且干净地重用 ByteBuffer 的代码),而不会产生不必要的混乱代码。

If I were you, I just wouldn't use an Iterator -- I'd write a different API (possibly quite dissimilar from Iterator, even) and implement that. For example, you might write a new API that takes as input the ByteBuffer to write the message into, so users of the API could control whether or not the buffer gets reused. That seems reasonably intuitive (the user can write code that obviously and cleanly reuses the ByteBuffer), without creating unnecessarily cluttered code.

这篇关于一个迭代并返回相同对象的迭代器。不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆