I'd like to simplify the nested if statement, but I'd like you to teach me how to write it well.

Asked 2 months ago, Updated 2 months ago, 3 views

I would like to know how to correct the following implementation.

private boolean isChange(String oldStr, String newStr){
 if(StringUtils.isEmpty(oldStr)){
  if(StringUtils.isEmpty(newStr)){
    return true;
  } else {
    return false;
  }
 } else if(StringUtils.isEmpty(newStr)) {
  return true;
 }
 if(!oldStr.equals(newStr)){
  return true;
 }
 return false;
}

java java8

2022-09-30 13:52

2 Answers

The condition that returns true is
if new is empty and old.epual(new) is false. In other words,

private boolean isChange(old,new){
  if(StringUtils.isEmpty(new)){
    return true;
  } else {
    return!old.equal(new)
  }
}

If I want to make it shorter, I think I can go downstairs.
I don't recommend it because it's less readable.

return StringUtils.isEmpty(new)?(true): (!old.equal(new))

"Also, ""new"" is a reserved word, so it is better to use the appropriate variable name."
There is no argument type declaration, so it should be appropriate.


2022-09-30 13:52

I would like to know how to correct the following implementation.

Based on the isChange method name, I interpreted it as a way to create a method that returns true if there is a change between old and new, and false if there is no change.

The following is an example of code modification.I don't use StringUtils.
Do not identify null with the " empty string. If you change from null to ", you determine that the reverse has also changed.

private boolean isChange(String oldStr, String newStr){
    if(oldStr==null&newStr==null){
        return false;// No variation
    }
    else if(oldStr==null||newStr==null){
        return true; // with variation
    }
    else if(newStr.equals(oldStr)){
        return false;// No variation
    } else{
        return true; // with variation
    }
}

I looked into StringUtils by referring to metropolis's comments.
The following code identifies the null and the " empty string, and if you change from null to ", the reverse is also determined to be unchanged.

if(StringUtils.isEmpty(oldStr)&StringUtils.isEmpty(newStr)){
    return false;
}
else if(StringUtils.equals(oldStr, newStr)){
    return false;
} else{
    return true;
}

The following code does not identify the null with the " empty string. If you change from null to ", the reverse is also considered variable.

private boolean isChange(String oldStr, String newStr){
    return!StringUtils.equals(oldStr, newStr);
}


2022-09-30 13:52

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.