Reputation: 693
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
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
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
Reputation: 19956
this
if it is not necessary.StringUtils.trimToEmpty()
from Apache Commons org.apache.commons.lang3
can be used here
public String getFirstOrLastNameOrBoth() {
return trimToEmpty(getFirstname()) + trimToEmpty(getLastname());
}
Upvotes: 0
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
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
Reputation: 1061
public String getFirstOrLastNameOrBoth() {
return (getFirstname() == null ? "" : getFirstname())
+ (getLastname() == null ? "" : getLastname());
}
Upvotes: 4