I'm trying to find out whether it would be a good idea to have flattened constructors for each of my POJO classes for composite primary or foreign key properties. Consider the following bean:
This is an example of an entity class whose primary key is composed of two other composite primary keys, a score and a team member. There are two naive general ways to construct a new object of that class:
1. Call the default constructor and several setters, which IMO is all but handy to code (I agree with http://www.javapractices.com/topic/TopicAction.do?Id=84)
2. Call a constructor that accepts at least two objects of the primary key classes this entity class' ID class is composed of, like
In any case, the second is better than the first, but it still requires me to construct the object with the following call:
This is everything but ease to code. If I now flattened the Score and TeamMember constructors to avoid having to instantiate the ID classes beforehand, I would get
I would then get
Already better, but there's room for more: flatten PlayerStat's constructors to yield:
This would finally allow me to construct a player stat object with
If I flattened all ID class constructors, you could further get rid of the redundant ID class constructor calls in the entity classes' constructors, but that's just an optimization.
Now the question is:
Isn't the described just a somewhat "mechanic" pattern that should apply in general when writing entity and ID classes that have composite keys? Are there any downsides to applying this as a general strategy, composite-key entity and ID classes alike? I believe there are more advantages than disadvantages for implementing flattened constructors.