Java Beans: What am I missing?

前端 未结 5 1958
别跟我提以往
别跟我提以往 2021-02-07 06:08

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. B

5条回答
  •  执念已碎
    2021-02-07 06:37

    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.

提交回复
热议问题