java - Sane pattern for immutable pojos and single field changes -
usually i'd love pojos immutable (well, contain final
fields java understands immutability). current project, constant pattern need change single field pojo. working immutable pojo's in scenario seems cumbersome.
how go having pojo's bunch of fields , each field should able "please give me copy of pojo 1 field changed"?
big plus here can use composable functions. "start immutable pojo, push through bunch of unaryoperators , give me new immutable pojo".
yes, that's common pattern - bunch of methods with
prefix. each with*
method "changes" single field, can have:
person jon = new person("jon", "skeet"); person holly = jon.withfirstname("holly"); // holly skeet
you can chain calls together, too:
person fred = jon.withage(...).withfirstname("fred").withjob(...);
note if end changing k fields in pojo n fields, you'll create k objects , need k * n assignments.
the implementation matter of calling big constructor existing field values , new one:
public person withfirstname(string newfirstname) { return new person(newfirstname, lastname, job, age, ...); }
i've used term "pseudo-mutator" kind of method - it's method sounds bit it's mutating something, it's more it's creating clone, mutating clone, returning in "frozen" state.
Comments
Post a Comment