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?

  • What happens if someone wants to update something to be null? Maybe nulls are disallowed in all your schemas? – Erik Eidt Apr 8 '16 at 15:07
  • If you have an entity with so many fields, then something is wrong in your dessign.. Why not implement these optional fields like Properties. Into a Map or Set ? – Laiv Apr 9 '16 at 14:24

If you don't want to have to amend your updateProduct() method for each field (and if you have many, many fields, that's perhaps fair enough), perhaps one of the following approaches can help:

a) provide your updates as a Map<String,Object> where the key is a field name, and the value is the updated value. Use reflection to find the corresponding field and amend that

b) similar to the above, but use reflection to find the fields in the 'update' Product and then set in the destination object. Unlike the first solution, you'll have to further determine the subset of fields being updated

You could perhaps avoid reflection by storing the fields underlying Product as a Map (or similar structure) and provide appropriate accessors. By doing that you can simply update the underlying collection.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.