Catalina
Catalina

Reputation: 693

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

Upvotes: 2

Views: 595

Answers (6)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

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, "");

Upvotes: 3

toliosg
toliosg

Reputation: 46

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.

Upvotes: 0

v.ladynev
v.ladynev

Reputation: 19956

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

Upvotes: 0

Mohaafly
Mohaafly

Reputation: 41

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

Upvotes: 0

Ashton
Ashton

Reputation: 11

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

Upvotes: 0

Ralf Renz
Ralf Renz

Reputation: 1061

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

Upvotes: 4

Related Questions