File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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: 3152

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

Joined: Apr 06, 2010
Posts: 4543

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:
subject: Question regarding reference direction
It's not a secret anymore!