It's not a secret anymore!
The moose likes Servlets and the fly likes Beans vs. Attributes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Beans vs. Attributes" Watch "Beans vs. Attributes" New topic

Beans vs. Attributes

Elizabeth Reynolds

Joined: Mar 31, 2002
Posts: 24
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

Joined: Jan 07, 1999
Posts: 6920
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.

    Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    subject: Beans vs. Attributes
    It's not a secret anymore!