I wrote a builder to set some configurations. One of the builder's method is edit(BusinessObject)
. Now I got the requirement which leads to the same config except replacing this method by copy(BusinessObject)
. So the current implementation would be:
public Config editObject(BusinessObject object) {
return new ConfigBuilder()
.config1(p1)
.config2(p2)
.config3(p3)
...
.edit(object)
.build();
}
public Config copyObject(BusinessObject object) {
return new ConfigBuilder()
.config1(p1)
.config2(p2)
.config3(p3)
...
.copy(object)
.build();
}
class ConfigBuilder {
ConfigBuilder edit(BusinessObject o) {
// prepare some settings
return this;
}
ConfigBuilder copy(BusinessObject o) {
// prepare some other settings
return this;
}
}
To avoid duplicated code (except this one line everything else is the same) I want to extract it to a new method with an additional parameter like Function<BusinessObject, ConfigBuilder> prepare
.
But I'm stuck how to solve it. The builder instance will be created outside of editObject
/copyObject
's scope so editOrCopy(object, ConfigBuilder::copy)
does not work since this method is not static.
Any ideas?