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.
However I would be even more tempted to take a good look at the class and decide whether it is time to split the class in two - at which point the problem will go away.
Ultimately you may be trying to implement the Composite Pattern. In that case there shouldn't be a collection of "stuff" only one single "stuff". The only collection present should be foos - and your problem goes away. Foo objects acting as leaves store a single "stuff" while Foo objects acting as nodes only store other Foo objects in the foos collection.
BTW, I've edited the code to highlight the differences of objects contained in the Collections.
It is my intention to use the composite pattern! The original Foo class initially just contains one Collection, namely stuff. Following that, a change request commanded that Foo must be able to nest other Foos.
1) Perhaps I don't understand the pattern properly. I cannot see the use of leaf nodes in my situation. All Foo are composites. And the ones with an empty collection of children Foos are the leafs.
Foo objects acting as leaves store a single "stuff" while Foo objects acting as nodes only store other Foo objects in the foos collection.
Foo has a 1-many relation with Bar (see updated code).
2) I think I can learn somethings from the FactorParameter link that you sent. For now, as a stopgap measure, I am using a conditional within the accept method.
Joined: Aug 19, 2005
Originally posted by Pho Tek: Foo has a 1-many relation with Bar (see updated code).
Your new solution is problematic as it requires the visitor to implement the .interestedInFoo() method, basically strengthing the coupling between the visitor and the class being visited.
I appreciate that in your original design "Foo has a 1-many relation with Bar". However once you use the composite you should convert the "Foo has a 1-many relation with Bar" to "Foo has a 1-many relation with Foo objects which each have one Bar" which is just a special case of "Foo has a 1-many relation with Foo objects".
There is another implementation possibility. If you take a look at the composite pattern you should notice that both the Leaf and the Composite implement the same Component interface. In your case the Component interface is the IVisitable interface. Keep your Foo Class as is and use it as the Leaf Class. Create a new class FooFoo which manages the new IVisitable collection (Foos or other FooFoos) and implements the IVisitable interface. FooFoo then simply delegates the accept request to all of its IVisitables. [ November 22, 2006: Message edited by: Peer Reynders ]