Monday, February 15, 2010

Parent-Child Relationship in Java Business Logic Beans

There must be good tips and info out there on the net about best practices for designing Java beans business objects, etc. I don't mean basic stuff like getters/setters, but much more subtle questions like when to hide constructors, how to deal with parent-child objects and what sort of methods to expose for that, etc.
Somehow I never found good info on that (not that I tried too hard), and my classes didn't cover it.

Here's my take on the parent-child relationship between Java objects. Say there are two classes: Customer and Contact (a typical sales-app situation). Each customer has multiple contacts - a simple one-to-many relationship. The customer object keeps track of the child contacts with a collection, and the contact maintains a parent customer reference.

Question: how to handle creating new contact objects?

In contact class:
// package-private constructor
Contact(Customer c, parameters...) {
  this.customer = c; // keep parent reference
  // deal with other parameters
}
In customer class:
public Contact createContact(parameters...) {
  Contact c = new Contact(this, parameters...);
  this.contacts.add(c); // update children collection
  return c;
}
Why not expose the contact constructor directly and have it update the customer contacts collection? Adding to the children collection is altering object state - it is best to keep that inside the customer class.

Even in terms of readability this makes more sense. When humans say "customer", the meaning includes all the relevant contacts, etc. When we create a contact we change customer state, first and foremost. So it makes sense to initiate that change with the customer object.

No comments: