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

前端 未结 7 1330
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    Summarizing other answers I think that:

    • Inmutability facilitates correctness (structs can be passed by reference and you know nothing will be destroyed by a faulty/malicious client) and code simplicity
    • Mutability facilitates homogeneity: Spring and other frameworks create an object with no arguments, set object properties, and voi là. Also make interfaces easier using the same class for giving data and saving modifications (you don't need get(id): Client and save(MutableClient), being MutableClient some descendant of Client.

    If there were an intermediate point (create, set properties, make inmutable) maybe frameworks would encourage more an inmutable approach.

    Anyway I suggest thinking in inmutable objects as "read only Java Beans" stressing the point that if you are a good boy and don't touch that dangerous setProperty method all will be fine.

提交回复
热议问题