Search code examples
javaif-statementnullrefactoringnullable

How to avoid multiple If Statements in Java?


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;
}

Solution

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