Chapter 5. Beans to Values

Many Java projects have settled on mutable JavaBeans or POJO (plain old Java object) conventions for representing data. Mutability brings complications, though. Why are immutable values a better choice, and how can we reduce the cost of mutability in a codebase?

Beans

As we discussed in “Bean Style”, JavaBeans were introduced to allow the development of drag-and-drop GUI builders in the Visual Basic style. A developer could drop a button onto a form, change its title and icon, and then wire in an on-click handler. Behind the scenes, the GUI builder would write code to instantiate a button object and then call setters for the properties that the developer had changed.

To define a JavaBean, a class needs a default (no-argument) constructor, getters for its properties, and setters for its mutable properties. (We’ll gloss over the Serializable requirement, because even Sun never really took this seriously.) This makes sense for objects that have a lot of properties. GUI components typically have foreground and background colors, font, label, borders, size, alignments, paddings, and so on. Mostly the defaults for these properties are fine, so calling setters for just the special values minimizes the amount of code to be generated. Even today, a mutable component model is a solid choice for GUI toolkits.

When JavaBeans were introduced, though, we thought of most objects as mutable, not just UI components. I mean, why not? The point of objects was to encapsulate ...

Get Java to Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.