• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

211
Views
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?

over 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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!

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error