Alex Rivera | Logout

Are Java Beans as data storage classes bad design?

Asked 2010-06-25T00:55:13.940
10

Usually JavaPractices.com is a good site with good idea's, but this one troubles me: JavaBeans are bad.

The article cites several reasons, mainly that the term JavaBean means "A Java Bean is a reusable software component that can be manipulated visually in a builder tool." not Data storage, violates certain patters, and is more complex.

Now I can agree with the last one, but in my eyes JavaBeans in a list makes a lot more sense than nested Maps. The article claims that database mapping frameworks should call constructors, not set* methods, and the object should be immutable. In my mind however, calling set* methods when trying to build an object is easier to read than new MappedObject("column1", "column2", "yet another column", "this is stupid");

I also use the JavaBean style class for other things besides database mapping, eg for an IRC bot, having an object per user that gets updated with various things. I don't want to create a new object every time new information is given, I want to add it to an existing one.

So my question: Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?

Edit
Report

1 Answer

20

It seems that you are misreading the text.

Now I can agree with the last one, but in my eye's JavaBeans in a list makes alot more sense than nested Maps

The text never mentions nested maps as an alternative ( yiack )

...should call constructors, not set* methods, and the object should be immutable

This is a good practice, specially useful when dealing with threads.

But we can't say that using setters is baaad either, specially when a single thread is using the object. That's perfectly safe.

I don't want to create a new object every time new information is given, I want to add it to an existing one.

That's fine, as long as you control the object there is no problem with this, some other may find easier to just create a new object.

Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?

No, is not a bad practice. Is not perfectly safe either. Depends on the situation.

The problem with mutable objects ( not with JavaBeans per se ) is using different threads to access them.

You have to synchronize the access to avoid one thread modify the object while other is accessing it.

Immutable objects doesn't have this problem, because, .. well they can't change, and thus, you don't have to synchronize anything.

To make sure an object is immutable you have to declare your attributes as final.

class MyBean  {
    private final int i;
}

If you want to assign a reasonable value to MyBean.i you have to specify it in the constructor:

 public MyBean( int i ) {
     this.i = i;
 }

Since the variable is final, you can't use a setter. You can just provide a getter. <

answered 2010-06-25T01:31:42.583

Your Answer