Are Java Beans as data storage classes bad design?

后端 未结 6 1532
挽巷
挽巷 2021-02-14 11:49

Usually JavaPractices.com is a good site with good idea\'s, but this one troubles me: JavaBeans are bad.

The article cites several reasons, mainly that the term JavaBea

6条回答
  •  爱一瞬间的悲伤
    2021-02-14 12:13

    My objection to using JavaBeans as data storage classes is that they allow for objects with inconsistent state. In the typical use case for such beans, you have the following steps:

    • instantiate the class;
    • set the first property;
    • set the second property;
    • ...
    • set the final property;
    • use the object instance.

    Now your class is ready to use. So what's the problem here? Between instantiating the class and setting the final property you have an object which is in an internally-inconsistent or unusable state, but there's nothing preventing you from accidentally using it. I prefer a system where the class is automatically in a consistent, usable state upon instantiation. For this reason I prefer to either pass in all the initial state in the constructor or, if said initial state is too complicated, pass in the initial state in the form of a hash map or set or the like. The use case scenario is now:

    • (Optional: set up a parameters object);
    • instantiate the class;
    • use the object instance.

    At no point in this work flow is it possible for me to accidentally start using an object with inconsistent state. If I use a parameters object, it is not directly used for anything at all and its contents will be vetted upon instantiation of my main class. The main class itself, upon returning from instantiation, will give me an object instance that is of immediate use.

    This kind of setup is best for simpler objects, of course. For more complicated objects with things like optional properties, etc. you'll want to go a step farther and use something like the Builder pattern that others have pointed you toward. Builders are nice when you have more complicated scenarios, IMO, but for simpler, more straightforward parametrization just using constructor arguments or a parameters object of some sort is more than enough.

提交回复
热议问题