Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
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 4 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 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!