javajavabeans

Java Beans: What am I missing?


I'm wondering if I'm missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. Beans seem to go directly against this and generally feel clunky. What capabilities am I missing out on by not building my objects as Beans?


Solution

  • It sounds like you are on the right track. It's not you who's missing the point of Java Beans, it is other programmers that are misusing them.

    The Java Beans specification was designed to be used with visual tools. The idea was that an application designer would be able to configure an instance of an object interactively, then serialize (or generate code for) the configured bean, so that it could be reconstructed at runtime; the intent was that it would not be mutated at runtime.

    Unfortunately, a lot of developers don't understand that accessors violate encapsulation. They use structs instead of objects. They don't see anything wrong with other classes, even other packages, having dependencies on a class's data members.

    Of course, you will in general have the need to configure instances of your objects. It's just that this should be done through some sort of configuration feature. This might be a dependency injection container, a "BeanBox" style visual tool, or simply reading JSON, XML, or properties files that you wrote by hand. The key is that at runtime these objects are effectively immutable; clients just invoke their operations, they don't access their properties.