Usually I'd love all my POJOs to be immutable (well, to contain only final
fields as Java understands immutability). But with my current project, a constant pattern is that I need to change a single field from a POJO. Working with immutable POJO's in this scenario seems cumbersome.
How would you go about having POJO's with bunch of fields and for each field you should be able to say "please give me a copy of this POJO but with this one field changed"?
Big plus here would be something that I can use with composable Functions. "Start with this immutable pojo, then basically push it through bunch of UnaryOperators and give me back new immutable pojo".
Yes, that's a fairly common pattern - usually with a bunch of methods with a with
prefix. Each with*
method "changes" a single field, so you can have:
Person jon = new Person("Jon", "Skeet");
Person holly = jon.withFirstName("Holly"); // Holly Skeet
You can chain the calls together, too:
Person fred = jon.withAge(...).withFirstName("Fred").withJob(...);
Note that if you end up changing K fields in a POJO with N fields, you'll create K objects and need K * N assignments.
The implementation is usually just a matter of calling a big constructor with the existing field values and the new one:
public Person withFirstName(String newFirstName) {
return new Person(newFirstName, lastName, job, age, ...);
}
I've used the term "pseudo-mutator" for this kind of method - it's a method which sounds a bit like it's mutating something, but it's more like it's creating a clone, mutating the clone, then returning it to you in a "frozen" state.
See more on this question at Stackoverflow