1

I have finished learning about java beans, and from what I understand, they are regular classes just that they are serializable, all the properties are private and are accessed through getter and setter methods, and they contain a public no arguments constructor.

I can see the advantages and disadvantages of writing bean classes, but have trouble understanding when I should write Java beans and when I should not. When building a class library, what types of classes would benefit from being beans and which would not?

1 Answer 1

7

Let us look at what properties Java beans have:

  1. No-argument constructor.
  2. Getters and setters for all state.
  3. Serializable.

What does this mean, however?

  1. Can be constructed easily without dependencies.
  2. Simple state.
  3. Can be easily sent across a stream, to e.g. a file or a socket.
  4. No mention of behavior: while not forbidden, we are encouraged to have stateful but behaviorless objects.

This perfectly describes an object that models state, not behavior. In popular idioms such as MVC or MVVM, a bean is a model.

If you have an object that represents data that can be passed around between objects or with other systems, that is a perfect candidate for a Java bean.

If you have an object that performs actions and directs traffic, that is not a candidate for a Java bean. If you have an object that manages a view, that is, converts state into a form suitable for presenting to the user, that is also not a candidate for a Java bean.

That being said, the three properties are not exclusive to Java beans and other objects may technically fall into the bean category. However, beans are just as much how we think about and use an object as the three constraints mentioned above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.