'Refactor method and remove extra local variable(remove binding)
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?
Solution 1:[1]
Just split Foo to two methods
public void updateNameIfNeed(User user) {
if (needUpdateName(user.getName())) {
user.setName("new name");
userRepository.update(user);
}
}
public void updateAgeIfNeed(User user) {
if (needUpdateAge(user.getAge())) {
user.setAge(42);
userRepository.update(user);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kai-Sheng Yang |
