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?

asked Feb 3, 2017 at 18:44

1 Answer 1

8

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.

answered Feb 3, 2017 at 19:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.