Why shouldn't I use immutable POJOs instead of JavaBeans?

前端 未结 7 1344
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 06:27

I have implemented a few Java applications now, only desktop applications so far. I prefer to use immutable objects for passing the data around in the application instead of

7条回答
  •  一个人的身影
    2020-12-04 06:56

    Prefer JavaBeans When

    • you have to interact with environments that expect them
    • you have lots of properties for which it would be inconvenient to do all initialization on instantiation
    • you have state that is expensive or impossible to copy for some reason but requires mutation
    • you think at some point you may have to change how properties are accessed (e.g. moving from stored to calculated values, access authorization, etc.)
    • you want to conform to coding standards that mindlessly insist it is somehow more "object-oriented" to use JavaBeans

    Prefer Immutable POJOs When

    • you have a small number of simple properties
    • you do not have to interact with environments assuming JavaBean conventions
    • it is easy (or at the very least possible) to copy state when cloning your object
    • you don't ever plan on cloning the object at all
    • you're pretty sure that you don't ever have to modify how properties are accessed as above
    • you don't mind listening to whining (or sneering) about how your code isn't sufficiently "object-oriented"

提交回复
热议问题