So I am surprised that doing a search on google and stackoverflow doesn\'t return more results.
In OO programming (I\'m using java), how do you correctly implement a
There's no 100% surefire way to maintain the integrity.
The approach which is usually taken is to use one method to construct the relationship, and construct the other direction in that same method. But, as you say, this doesn't keep anyone from messing with it.
The next step would be to make some of the methods package-accessible, so that at least code which has nothing to do with yours can't break it:
class Parent {
private Collection children;
//note the default accessibility modifiers
void addChild(Child) {
children.add(child);
}
void removeChild(Child) {
children.remove(child);
}
}
class Child {
private Parent parent;
public void setParent(Parent parent){
if (this.parent != null)
this.parent.removeChild(this);
this.parent = parent;
this.parent.addChild(this);
}
}
In reality, you won't often model this relationship in your classes. Instead, you will look up all children for a parent in some kind of repository.