Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding reference direction

 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic