Let's say I have a Farmer class, and a Farmer has a collection of Pigs.
If I use an ORM like Hibernate, I can cascade updates to a Farmer's Pig collection, such that I can do something like this from my controller:
Pig pig = new Pig("Charlie");
farmer.addPig(pig);
farmerService.save(farmer);
My farmer service doesn't know anything about Pigs. Depending on the requirements of the application, I might not even need a Pig DAO at all. I'm only concerned with Farmers.
Cool, but what happens when a Pig gets turned into bacon?
farmer.removePig(pig);
farmerService.save(farmer);
The problem here is that in a stateless web application I need some way to create a Pig that I'm going to pass to a Farmer's removePig method.
I could do:
// manual search Farmer's collection - requires loading all pigs.
// Yes, I could just pass id to removePig, but it confuses the example
pig = farmer.getPigById(id);
farmer.removePig(pig);
farmerService.save(farmer);
or
// loads up a pig, and hopefully it belongs to the farmer
pig = farmerService.getPigById(id);
farmer.removePig(pig);
farmerService.save(farmer);
The latter seems better, but if I'm going to add a getPigById() method to my farmerService, I might also just have a savePig() method. This would change the focus from the Farmer to the Pig.
pig = farmerService.getPigById(id);
farmerService.removePig(pig);
Aha, and look it's even less code. However, it violates the logical view of wanting to work with Farmers and their pig collections, not individual pigs. I'm no longer explicitly removing a Pig from a farmer, it's all implicit and backwards.
I seem to run into this problem a lot. The class that should be in focus is Farmer. Pigs are secondary. But it's hard to work with collections of Pigs without sliding down the slope into working with individual Pigs whose changes are simply reflected when Farmers are reloaded from persistence.
What advice can you offer me in this matter?