Home > Software design >  How to avoid multiple If Statements in Java?
How to avoid multiple If Statements in Java?

Time:04-16

How to refactor this method?

public String getFirstOrLastNameOrBoth() {
    if (this.getFirstname() != null && this.getLastname() != null) {
        return this.getFirstname()   this.getLastname();
    } else if (this.getFirstname() != null && this.getLastname() == null){
        return this.getFirstname();
    } else if (this.getLastname() != null && this.getFirstname() == null){
        return this.getLastname();
    }
    return 0.0;
}

CodePudding user response:

    public String getFirstOrLastNameOrBoth() {
        return (getFirstname() == null ? "" : getFirstname()) 
               (getLastname() == null ? "" : getLastname());
    }

CodePudding user response:

There's no need to invoke getter in the class in order to access a field. Use the field name instead.

Instead of null-checks, you can make use of noneNullOrElse() static method of the Objects utility class.

return Objects.requireNonNullElse(firstName, "")  
       Objects.requireNonNullElse(lastName, "");

CodePudding user response:

public String getFirstOrLastNameOrBoth() {
    if(this.getFirstname() == null && this.getLastname() == null) {
        return "0.0";
    }
    
    return (this.getFirstName() != null ? this.getFirstName() : "")  
            (this.getLastname() != null ? this.getLastname() : "");
}

CodePudding user response:

if (this.getFirstname() != null && this.getLastname() != null) {
   return this.getFirstname()   this.getLastname();
} else {
   return Optional.ofNullable(this.getFirstname()).orElseGet(() -> Optional.ofNullable(this.getLastname()).orElseGet(() -> "0.0"));
}

CodePudding user response:

  1. Don't use this if it is not necessary.
  2. Use library methods to work with strings.

StringUtils.trimToEmpty() from Apache Commons org.apache.commons.lang3 can be used here

    public String getFirstOrLastNameOrBoth() {
        return trimToEmpty(getFirstname())   trimToEmpty(getLastname());
    }

CodePudding user response:

Another thing you can do is to transfer the if statements in the get methods, so you can check there whether something is null or not. More specifically:

 public String getFirstname() {
    if (firstname != null){
    return firstname;}

    return "";
}

public String getLastname() {
    if (lastname!= null){
        return lastname;}

    return "";
}
public String getFirstOrLastNameOrBoth() {
   return (getFirstname()   " "   getLastname()).trim();
}

This way is called the extract method and in this case, you'll be able to check for null not only in the last method but also in the getters. Therefore I think it is safe. I have also used the trim method in order to remove the spaces in the beginning in case the first name is null.

  • Related