![](/img/trans.png)
[英]Clean way of avoiding NullPointerException in equals checks
[英]Alternate way to code multiple checks for NullPointerException, JAVA 8
在JAVA 8中還有更好的方法編寫此代碼嗎?
if (info1 != null && info1.getId() != null && info1.getPartyNumber()!= null) {
billing.setSenderId(info1.getId());
billing.setSenderNumber(info1.getPartyNumber());
}
if (info2 != null && info2.getId() != null && info2.getPartyNumber()!= null) {
billing.setReceiverId(info2.getId());
billing.setSellerNumber(info2.getPartyNumber());
}
..
..
提前致謝。 注意:我研究了Optional.ofNullable()
但是不確定在進行多次檢查時是否真的有幫助?
這是我能想到的最好的方法。 我會讓您決定它是否更干凈:
Optional<Info> oInfo1 = Optional.ofNullable(info1);
oInfo1.map(Info::getId).ifPresent(billing::setSenderId);
oInfo1.map(Info::getPartyNumber).ifPresent(billing::setSenderNumber);
Optional<Info> oInfo2 = Optional.ofNullable(info2);
oInfo2.map(Info::getId).ifPresent(billing::setReceiverId);
oInfo2.map(Info::getPartyNumber).ifPresent(billing::setSellerNumber);
請注意,這與原始設置略有不同,因為它可能會設置一個字段,即使另一個字段為null。
如果您想使用Optional
重寫它,它可能看起來像這樣:
Optional.ofNullable(info1)
.filter(i -> i.getId() != null)
.filter(i -> i.getPartyNumber() != null)
.ifPresent(i -> {
billing.setSenderId(info1.getId());
billing.setSenderNumber(info1.getPartyNumber());
});
僅當info1
不為null
且匹配指定為Optional.filter
參數的所有條件時,我們才對其進行處理。 因此,僅在info1 != null
和info1.getId() != null
以及info1.getPartyNumber() != null
的情況下,才會執行Consumer
。 這是編碼多個檢查的另一種方法 。 它執行您的代碼所執行的操作。
同樣的方法適用於info2
。
Optional
的流暢API與多行符號相結合,將每個條件都分解為自己的行。 IMO使得代碼易於閱讀,因此易於理解。 它盡可能保持原始代碼的簡潔性和清晰度,並且仍然以相同的方式運行。
如果您在源代碼中復制代碼,則應三思而后行。 我認為您的測試很好,但我會為此提供一種方法,因此您的代碼如下所示:
if(isComplete(info1){....} if(isComplete(info2){....}
如果您的多次重復遵循一個精確的模式(例如,每個奇數重復都設置了一個receiver
,否則為sender
),或者可以將此模式提取到Set<Integer>
,則可以使用Map<Integer, Info>
,其中鍵是Info
的ID ,然后對其進行迭代並僅設置所選項目。
List<Info> list = ... // List of Info
Map<Integer, Info> map = list.stream() // Stream
.filter(Objects::nonNull) // Filter null values
.filter(i -> i.getId() != null && i.getPartyNumber() != null) // Filter null fields
.collect(Collectors.toMap(Info::getId, i -> i)); // Collect to Map<Integer, Info>
for (int i=0; i<10; i++) { // The number of repetitions
if (map.containsKey(i)) { // If the ID was not filtered
Info info = map.get(i); // Get the Info
// Here the pattern comes
if (i % 2 == 0) { // you can either compare with a
// predefined Set of IDs
billing.setSenderId(info.getId());
billing.setSenderNumber(info.getPartyNumber()); // Sender
} else {
billing.setReceiverId(info.getId()); // Receiver
billing.setSellerNumber(info.getPartyNumber());
}
}
}
解決方案將有所不同,並取決於可能的設置數量以及sender
和receiver
。 另外,模式的計算可能基於不同的邏輯-我建議針對ex進行驗證。 Set<Integer> senders
,它將包含適合設置為發送者的ID,接收者和其他可能性也是如此。
Info
,解決方案的長度都保持不變(除了將所有Info
收集到輸入list
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.