3 回答

TA貢獻2080條經驗 獲得超4個贊
通過命令式方法,您正在執行的這種類型的驗證會更好,但是我們可以在適當的地方使用lambda。
首先,我將signum在帖子中使用@ThomasKl?ger的建議,將重復條件與本地謂詞隔離開,因為在這種特定情況下,該條件比更為合適intValue。
Predicate<BigDecimal> criteria = b -> b != null && b.signum() < 0;
那么您的命令式方法將如下所示:
for (GlobalPricingRequest globalPricingRequest : globalPricingRequests) {
isValidOrElseThrowBadRequestException(globalPricingRequest.getFeePerTransact(), criteria);
for (EventTypePricingMapping eventTypePricingMapping : globalPricingRequest.getEventTypePricingList()) {
isValidOrElseThrowBadRequestException(eventTypePricingMapping.getFeePerRevenue(), criteria);
}
}
其中isValidOrElseThrow定義為:
public static void isValidOrElseThrowBadRequestException(BigDecimal data, Predicate<BigDecimal> criteria) throws Exception { // change the exception to the specific one you're using
if(criteria.test(data)) throw ExceptionHelper.badRequest("Fee Per Transaction can't be less than zero");
}
只需在此處和此處進行一些隔離,就可以使代碼更具可讀性。

TA貢獻1780條經驗 獲得超1個贊
您可以使用流兩次,并提高代碼的可讀性,如下所示:
Predicate<BigDecimal> feeCheck =
feePerTransactOrRevenue -> feePerTransactOrRevenue != null
&& feePerTransactOrRevenue.intValue() < 0;
boolean globalRequestCheck = globalPricingRequests.stream()
.map(GlobalPricingRequest::getFeePerTransact)
.anyMatch(feeCheck);
boolean eventTypeCheck = globalPricingRequests.stream()
.map(GlobalPricingRequest::getEventTypePricingList)
.flatMap(List::stream)
.map(EventTypePricingMapping::getFeePerRevenue)
.anyMatch(feeCheck);
// if any of the element matches the condition, throw the exception
if (globalRequestCheck || eventTypeCheck) {
throw ExceptionHelper.badRequest("Fee Per Transaction can't be less than zero");
}
添加回答
舉報