如何重構這個方法?
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;
}
uj5u.com熱心網友回復:
public String getFirstOrLastNameOrBoth() {
return (getFirstname() == null ? "" : getFirstname())
(getLastname() == null ? "" : getLastname());
}
uj5u.com熱心網友回復:
無需在類中呼叫 getter 即可訪問欄位。請改用欄位名稱。
您可以使用實用程式類的noneNullOrElse()靜態方法來代替空值檢查。Objects
return Objects.requireNonNullElse(firstName, "")
Objects.requireNonNullElse(lastName, "");
uj5u.com熱心網友回復:
public String getFirstOrLastNameOrBoth() {
if(this.getFirstname() == null && this.getLastname() == null) {
return "0.0";
}
return (this.getFirstName() != null ? this.getFirstName() : "")
(this.getLastname() != null ? this.getLastname() : "");
}
uj5u.com熱心網友回復:
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"));
}
uj5u.com熱心網友回復:
this如果沒有必要,請勿使用。- 使用庫方法來處理字串。
StringUtils.trimToEmpty()來自 Apache Commons 的org.apache.commons.lang3可以在這里使用
public String getFirstOrLastNameOrBoth() {
return trimToEmpty(getFirstname()) trimToEmpty(getLastname());
}
uj5u.com熱心網友回復:
您可以做的另一件事是在 get 方法中傳輸 if 陳述句,這樣您就可以在那里檢查某些內容是否為空。進一步來說:
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();
}
這種方法稱為提取方法,在這種情況下,您不僅可以在最后一個方法中檢查 null,還可以在 getter 中檢查。因此我認為它是安全的。我還使用了 trim 方法,以便在名字為空的情況下洗掉開頭的空格。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460680.html
