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


Yes, David's statement "It is rather unintuitive (at least for a Java coder)
to use a getter to access a data structure that is modifiable in place" has
been bugging me since Friday ... I've been wondering why I don't think that
way ... Java being far from my first language.  Indeed, I've never adopted a
defensive stance to combat antipattern #1.  I assume if somebody hands me a
collection, it's mine to play with -- a habit I definitely picked up outside
the Java world.  Since I've been working a lot with Scala lately, this habit
is quite reinforced.

Also, thinking back, in Java 1.4 and before, untyped, non-generic
collections were so ugly to work with and required so much out-of-band
knowledge to properly cast and interact with, that they were typically not
something you would want to expose in a public way -- supplying a few useful
methods like addTypedObject(TypedObject typedObject) was certainly the way
to go.

Going forward, though, with the elegant syntax available for iteration, etc.
on collections typed with generics, the practice of exposing collections
(wrapped/subclassed, as you suggest, or not) is almost certainly going to
approach the same incidence in Java as in many other languages.  Which makes
antipattern #1 a large-ish potential problem ...

I wonder if this could be captured with a FindBugs pattern warning (you are
returning a mutable collection ... like what you get when you return a
mutable Date object) that could be disabled by attaching a @Modifiable
annotation or something to the returned object in question.

- R

Reply via email to