Trying to efficiently check to see if a new copy of the object has any different fields, and if they do, update the local ones and make a note of it. If any of the fields change then I need to persist the object to the database. I don't want to make that call if I don't have to, hence the boolean.
I couldn't think of a better way to do this without using reflection, but I don't want to use reflection here because of the lack of compiler-backed safety (would have string references to field names), and not all the fields are the same type (I have some Java 8 Instant fields in there).
What I really want to avoid is the book-keeping of having to remember to add or subtract to/from the sync method when the fields are modified. Obviously subtracting is not a big deal because the method will break, but adding is scary if someone doesn't remember to update the new field.
public boolean syncWithFieldsFrom(User currentUser) {
boolean doesUserNeedUpdating = false;
if (!StringUtils.equals(email, currentUser.email)) {
email = currentUser.email;
doesUserNeedUpdating = true;
}
if (!StringUtils.equals(firstName, currentUser.firstName)) {
firstName = currentUser.firstName;
doesUserNeedUpdating = true;
}
if (!StringUtils.equals(lastName, currentUser.lastName)) {
lastName = currentUser.lastName;
doesUserNeedUpdating = true;
}
if (!StringUtils.equals(fullName, currentUser.fullName)) {
fullName = currentUser.fullName;
doesUserNeedUpdating = true;
}
return doesUserNeedUpdating;
}