• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Beans vs. Attributes

 
Elizabeth Reynolds
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is so much flexibility in the way you can structure apps even within the standard frameworks such as MVC and struts.
My question is when should a bean be employed vs. using attributes? I'm finding that I can accomplish everything I want by setting and getting attributes in my servlets/jsp rather than creating beans.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To me this seems similar to deciding whether to have lots of simple member variables in a class, or a few more complex objects.
Using attributes is fine, but keep an eye out for the kind of things which might be "telling" you that you need to aggregate them:
  • If you have several methods which update the same set of attributes, group those attributes into a class.
  • If you find that adding a new attribute needs changes in lots of places in the code, group it with some others.
  • If some attributes depend on others, and must change if the others change, group them together.


  • And so on. I hope you are getting the picture.
    Note that I say nothing about "beans" in the above. JavaBeans are just objects, with regular class definitions. You should only use JavaBeans (with all the extra requirements of serializability and get/set accessors for all the internal state) instead of regular classes if you actually need the JavaBeans features. In a JSP situation, you might need to make a class into a JavaBean if you want to use the special JSP tags for creating and accessing JavaBeans instead of calling regular methods in scriptlets or custom tags.
    Please don't fall into the trap of writing lots of get/set accessors "just because". If you don't need it, don't code it. There are some interesting threads about "data holding" classes over in the "OO, UML and Refactoring" forum. please have a look around over there.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic