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

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

    Well it depends on what you're trying to do. If your working with a persistent layer, and you fetch some row from the database into a POJO, and you want to change a property and save it back, using JavaBean style would be better, especially if you have a lot of properties.

    Consider that your person, has a lot of fields like, first, middle, last name, date of birth, family members, education, job, salary etc.

    And that Person happens to be a female that just got married and accepted to have her last name changed, and you need to update the database.

    If you're using immutable POJO, you fetch a Person object representing her, then you create a new Person object to which you pass all the properties that you didn't change as they are, and the new last name, and save it.

    If it were a Java bean you can just do setLastName() and save it.

    It's 'Minimize mutability' not 'never use mutable objects'. Some situations work better with mutable objects, it's really your job to decide if making an object mutable will better fit your program or not. You shouldn't always say 'must use immutable objects', instead see how many classes you can make immutable before you start hurting yourself.

提交回复
热议问题