I have this class:
public class User {
private String name;
private int age;
//getters setters
}
I have a method, which updates a user object:
public void foo(User user) {
boolean needUpdate = false;
if(needUpdateName(user.getName())) {
user.setName("new name");
needUpdate = true;
}
if(needUpdateAge(user.getAge())) {
user.setAge(42);
needUpdate = true;
}
if(needUpdate) {
userRepository.update(user);
}
}
It's a simple example, only as an example. How can I refactor this code and remove needUpdate
variable?
If you want to remove the local variable you would loose the state that you had, so you will have to invoke 2 times the methods needUpdateName()
and needUpdateAge()
public void foo(User user) {
if(needUpdateName(user.getName()) || needUpdateAge(user.getAge()) ) {
if(needUpdateName(user.getName())) {
user.setName("new name");
}
if(needUpdateAge(user.getAge())) {
user.setAge(42);
}
userRepository.update(user);
}
}
Another more optimal way would be to introduce 2 new methods
boolean updateNameIfNeeded(User user, String newName)
boolean updateAgeIfNeeded(User user, Integer newAge)
So they would be something like
private boolean updateNameIfNeeded(User user, String newName) {
if (needUpdateName(user.getName())){
user.setName(newName);
return true;
} else {
return false;
}
}
Same for age
private boolean updateAgeIfNeeded(User user, Integer newAge) {
if (needUpdateAge(user.getAge())){
user.setAge(newAge);
return true;
} else {
return false;
}
}
So your main method then will become
public void foo(User user) {
if(updateNameIfNeeded(user, "new Name") || updateAgeIfNeeded(user, 42) ) {
userRepository.update(user);
}
}
This solution is more optimal because needUpdateName
and needUpdateAge
functions that make the checks are invoked only once!