Let's say I have a Person class that has a collection of Dog objects. The relationship is bidirectional.
public class Person {
private List<Dog> dogs;
// getter and setter for dogs
}
public class Dog {
private Person person;
// getter and setter for person
}
Ok now if I was just working with these objects, I would have methods in Person for adding a dog and removing a dog, so that the client isn't directly working with the collection.
public void removeDog(Dog dog) {
dogs.remove(dog);
dog.setPerson(null);
}
public void addDog(Dog dog) {
dog.setPerson(this);
dogs.add(dog);
}
or something along those lines.
My question comes when working with these objects in the service layer. I can add a new dog to a person via addDog and simply save the person which will automatically persist the new dog. However, removing a dog via removeDog and then saving the person will not automatically delete the dog from persistent storage...it'll just set the dog reference to null.
So I end up with something like:
Dog dog = dogDAO.getDogById(int id);
dogDAO.remove(dog);
Because this is a web app and Persons and Dogs are not maintained in memory, this works fine, and I never called Person.removeDog(). The next time I load up the Person who originally referenced this dog, it will not contain the dog because it was removed from storage. The same thing can apply to adding a dog:
Person person = personDAO.getPersonById(int id);
Dog dog = new Dog();
dog.setPerson(person);
dogDAO.save(dog);
Again this works fine even and I never called Person.addDog().
Is there any point to having the addDog and removeDog methods in my Person class then?