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. Eachwith*
method "changes" a single field, so you can have:You can chain the calls together, too:
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:
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.