Design advice: lists and containment
Bert Freudenberg
bert at impara.de
Sat Nov 5 19:22:13 UTC 2005
Am 05.11.2005 um 16:05 schrieb Jim Menard:
>
> So, a user has a bookmarks instance variable that is a collection. It
> would also simplify my code to let each bookmark have a user instance
> variable that "points" back to the user.
>
> 1) Is that kosher? Is it good practice to have a bookmark hold on
> to its user?
It's not "good" practice, IMHO. It creates a strong coupling between
bookmarks and users.
Also, the object reference graph is not acyclic anymore. DAGs are
easier to deal with, like when serializing.
> 2) To add a bookmark to a user, it now takes two steps:
>
> user bookmarks add: bookmark.
> bookmark user: user.
>
> Is there a better way? I could easily put that code into, say, a user
> method. Is that how it is commonly done?
Yes. Again, this reduces coupling, the code above does break the
encapsulation. There's even a law against this ;-)
It's called Demeter's Law, see, for example, http://
www.pragmaticprogrammer.com/ppllc/papers/1998_05.html
> 3) When I remove a bookmark from a user's collection, will the
> bookmark be GC'd? I think so, but I want to be sure.
Yes, if nothing else holds a reference to that bookmark.
> 4) The accessor method on user that returns the bookmarks means that
> callers can manipulate the list. My first instinct is to say, "Don't
> worry about it. I'm not developing a library, so I will know how to
> use the collection properly." Should I worry?
Well, it depends what your intentions are :)
> Should the accessor
> method return a copy of the bookmarks, so manipulation of the contents
> won't affect the user's bookmark list? If so, then I have to provide
> addBookmark: and removeBookmark: methods, right?
Yes, for the same reasons as above. As a more efficient alternative
to returning a copy, you could provide a bookmarksDo: method.
But, take all of that with a grain of salt ;-) Such rules are never
absolute. I, personally, would just expose the bookmarks collection
in that situation.
- Bert -
More information about the Squeak-dev
mailing list
|