Hi I have this project in which some Data Bean Classes used to represent entities have an enourmous number of fields. If I am to write the accessors and mutators ( getters and setters ) for all these fields the code length would grow huge and even managing it would be a nightmare . I have thought of an alternative solution. Instead of storing data properties as fields why can't I stuff all of them in a Properties or HashTable Object and have this as the only field of the data bean. That way I would have only a single accessor and mutator and all the properties would be stored as key value pairs. Is this a good solution? Or is it just another luring anti pattern? Can anyone suggest any other alternative solutions? eg.: instead of writing:
Siddhartha, It's mainly a matter of personal preference. If you use an IDE, it generates the getters/setters for you.
I find the minimal cost of maintaining the getters/setters is more than offset by the compile time safety my code has. With the Properties object approach, I could change the name of a field without changing all the properties references and have my code fail in subtle ways. With the getters/setters, the code wouldn't compile and I would know right away.
Note that sometimes an object with all those fields is crying to be split up into multiple objects. You mentioned it's a data bean, so that might not be the case here though.
We recently had good experience with simple code generation in a similar situation.
We wrote a simple Generator that parsed a file of the form
and generates the Java code from it, including fields, getters, setters, equals, hashcode and toString method.
Works really well.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Jul 07, 2005
Dear Jeanne and Ilja, Thanks a lot for answering my queries, and thanks especially for reminding the automated IDE or Ant based generation approaches for getters and setters. I almost forgot about it. It is true that a getter/setter based approach provides more security and robustness to the code than the Properties object based approach. I was just apprehensive ( read horrified ) about the bulk of the fields that was there in the initial draft of the class diagrams. But we are going to review and modify the design soon and I hope or rather pray that it has lesser fields per class. Once again thanks a lot for your generous help!! Regards Siddhartha