I have a "Product" class that has some ID, and multiple other fields, and a function updateProduct(id, Product update). The intention is that "update" only contains the changed information - other unchanged fields may be missing or null.
I currently have some code similar to the following:
Product updateProduct(long id, Product update) {
ProductBuilder builder = new Builder().basedOn(productDatabase.get(id));
if (update.getName() != null) {
builder.withName(update.getName());
}
if (...) {
// Builder.with...
}
if (update.getPrice() != null) {
builder.withPrice(update.getPrice());
}
return builder.build();
}
In essence, I want to take all the existing fields and apply the new ones over the top.
Is there a way I can better express this logic?
If I add a new Product property, I then need to update this method. While not a problem for me, it may be less obvious where the code is breaking in the future.
My Product class currently has lots and lots of fields, where most are optional - is having an if-statement for each of them avoidable in some way?