[英]Simplify java if statement
如果構造,我可以簡化這個java嗎? 對我來說似乎太冗長了,我想讓它更短。
A是持久性Object,如果第一次訪問它的上下文,它將為null。 比A是instatniated和給定內容,如果失敗,一些備份內容給A。
if (A == null) {
A = staticGetMethod();
if (A == null) A = new BackupAContent() { ... };
}
更新:或者您可以簡單地刪除嵌套,因為它仍然會以相同的方式運行。
if (A == null) {
A = staticGetMethod();
}
if (A == null) {
new BackupAContent() { ... };
}
應該管用:
if (A == null && (A = staticGetMethod()) == null) {
new BackupAContent() { ... };
}
將您的構建邏輯放在工廠方法中
if (objA == null) {
objA = getAInstance();
}
將Charles建議的代碼封裝到實現Factory_method_pattern的方法中
您可以使用三元運算符而不是if
語句:
a = a ? a : staticGetMethod();
a = a ? a : new BackupAContent();
也就是說,我堅持你所擁有的,說實話 - 除了我會為第二個條件添加一個塊而不是將該語句與其內聯。
這是查爾斯古德溫的代碼略有變化:
if (A == null && (A = staticGetMethod()) == null) {
new BackupAContent() { ... };
}
我使用AND而不是OR
我認為這是最好的方法:
if(A == null)
{
if((A = staticGetMethod()) == null) A = new BackupAContent() { ... };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.