Why shouldn't I use immutable POJOs instead of JavaBeans?
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"
I was surprised that the word Thread did not appear anywhere in this discussion.
One of the main benefits of immutable classes is that they are inherently more thread safe due to no mutable, shared state.
Not only does this make your coding easier, it'll also give you two performance benefits as a side effect:
Less need for synchronization.
More scope for using final variables, which can facilitate subsequent compiler optimisations.
I am really trying to move towards immutable objects rather than JavaBean style classes. Exposing the guts of objects via getters and setters should probably not be the default choice.
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.