This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
When I run my application, it will start populating the "foos" collection. Later instances of "Bar" are created and added to the "bars" collection. Each instance of "Bar" must contain a valid "Foo" instance from the "foos" collection. How do I actual ensure that a Bar is created with an actual reference to a member of a collection ?
If I do this:
I am getting a copy of the object rather than an actual reference.
No, Collections hold references to objects. Since references are just values, List.get(int) returns a copy of the reference, but it points to the original object. You'd have to call clone() on the object (if it supports cloning) or some custom copy() method to make a copy of the object itself.
To ensure that every Bar has a reference to a Foo contained in the foos collection, make the Root object responsible for creating Bars. Since the Root object manages both foos and bars, it should have the responsibility of maintaining integrity between them. This is an aspect of encapsulation.
I think I understand your suggestion. i.e. I need an Root.addBar( .. ) method which will enforce the constraint.
However, in my case; the "foos" collection is a dynamically generated permutation of some other values. So I have to create the "foos" collection first. Then add Bar instances one by one.
Furthermore, Bar instances may share a single Foo.
Joined: Aug 07, 2003
That's exactly what I was thinking. If you have addBar add the new Bar to the bars collection, then if in the future you modify the collection of foos you can verify that all Bars in bars still reference Foos in foos.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com