wood burning stoves 2.0*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Question regarding reference direction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Question regarding reference direction" Watch "Question regarding reference direction" New topic
Author

Question regarding reference direction

Unnar Björnsson
Ranch Hand

Joined: Apr 30, 2005
Posts: 164
I keep running into the same dilemma when Im programming, take for example a simple class Map and another class called Tree. On each map there are numerous trees, which would be more appropriate, the Map class containing an array of Tree instances or each Tree object to contain a reference to the Map object it belongs too, or even both?
Another example is if a parent should have children or should the children have a parent
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3068
    
  33

If it is a One-Many relationship- One parent having many childer/one map having many trees- You have a collection in the Owning Entity(Parent/Map) and not in the dependent(Tree/Children).


Mohamed Sanaulla | My Blog
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4384
    
    8

I'd say there's no hard and fast rule - it all depends on your use cases. In which direction do you need to navigate the relationship? Store the references to support this. And if you need to be able to navigate it in both directions, then have both objects store the reference.

Of course, if it's bidirectional you've got to make sure it stays consistent, and in that case I'd recommend giving one end of the relationship responsibility for managing both ends. For instance, parent.addChild(child) would call child.setParent(this), and other classes should only ever manipulate the link via parent.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question regarding reference direction