Stephan Koops wrote:

perhaps we could add a comment to the method setCookies and the other Collection setters that the developer should use the getter to get the Collection and add the elements to the collection directly.

I think that'd be a fine idea.

My view is that the problem arises from an issue in the Java language itself: all the collection objects have mutable interfaces.

If you compare with text, we have String, which can't change, and StringBuffer, which can. If a method returns a String, you know you can't mess with it, and it can't be changed underneath you. StringBuffer, on the other hand, implies one or both.

Mildly bad in itself, this combines with a pattern that's massively overused in Java: classes that are structs, not objects. In classic OO design, there need be no relationship between methods and internal states. In Java, though, the JavaBeans getter/setter paradigm encourages people to expose internal state.

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. (Personally, I almost always follow pattern #3.) Since it's hard to say what we mean in code, and since we're doing something unusual, we should certainly document it.

William



--
William Pietri - [EMAIL PROTECTED] - +1-415-643-1024
Agile consulting, coaching, and development: http://www.scissor.com/
Use your geek-fu to fight poverty: http://www.mifos.org/

Reply via email to