Home > Back-end >  how to avoid multiple if s in java
how to avoid multiple if s in java

Time:04-14

How to refactor this kind of function in java?

     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:

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"));
}
  • Related