Tim Peierls wrote:
On Feb 3, 2008 2:59 PM, William Pietri <[EMAIL PROTECTED]
<mailto:[EMAIL PROTECTED]>> wrote:
Because of this, returning a collection can mean one of four things:
1. I'm giving you my copy of the data; please don't change it
("return foo").
2. I'm giving you my copy of the data; you may change it
("return foo").
3. I'm giving you data that you can't change (E.g.: "return
Collections.unmodifiableList(foo)").
4. I'm giving you your own copy of the data, which you can do
with as you please ("return new ArrayList(foo)").
Here we mean #2, but I think the much more common case is #1.
#1 is bad practice, given that #3 is available.
I agree completely. However, it's unfortunately common practice, and you
can't tell the difference from the API alone. Combined with #3 and #4,
many people will assume they can't or shouldn't modify a returned
collection. I think that's what happened to our original poster here.
#2 is not unusual, but you have to be careful about specifying under
what conditions it is safe to modify the returned data.
Another option is to return not a pure collection, but some custom
object that behaves properly.
In this case I might make a Cookies object (which others might call a
CookieManager or a CookieJar). It could just subclass Set<Cookie>, but
it could also be its own class that implements, say, Iterable<Cookie>
and delegates a number of common collection-style methods to an
underlying collection.
I like this partly because it gives additional design flexibility, but
mainly because it documents that it's not just your average collection
of stuff.
William
--
William Pietri - [EMAIL PROTECTED] - +1-415-643-1024
Agile consulting, coaching, and development: http://www.scissor.com/
Can you see the future? Prove it at http://www.longbets.org/