开发中代码优化小方法
---------------------------------------------------------------------------------------------------------------------------------------------------------
1.校验字段:
第一:检验,报错直接抛出异常: Objects.requireNonNull(contactId);
第二:方法名,检查是否需要输出日志: if(printLogIfNeeded)
第三:对于sql查询方法、java中的方法名字的命名定义推荐: find..By/query..By/get..By
三个字段都不为null的:
if (List.of("a", "a", "a").stream().allMatch(Objects::nonNull)) {}
有2个条件任一匹配到:
if(Stream.of(InProgress, Queued).anyMatch(status -> Objects.equals(source.getStatusCd(), status))){}
if(Arrays.asList(dailyLimit, monthLimit).contains(type)){}
只要有一个不为空:
StringUtils.equalsAny(a,b,c)
boolean allNonBlank = StringUtils.isNoneBlank(str1, str2, str3);
检验查询结果是否 业务需要返回的code:
CustomerBuPO customerBu = Optional.ofNullable(foundationRepository.getBuByName(reqVO.getBuId()))
.orElseThrow(() -> new BusinessException(101, "buId not exist"));
---------------------------------------------------------------------------------------------------------------------------------------------------------
2.考虑有null值,但是要转换字段类型取值,都可以用这种方法:
loyTxnStg.setOrigPoints(Optional.ofNullable(source.getOrigPoints()).map(BigDecimal::valueOf).orElse(null));
或:
memTier.setSeqNum(Objects.requireNonNullElse(tier, Tier::new).getSeqNum());
或:
String birthDay = StringUtils.defaultIfEmpty(contact.getCustomBirthdayDay(), "1");
或:
String pointValue = posReqVO.getAccount1000Value() == null? "0":posReqVO.getAccount1000Value();
String pointValue = Optional.ofNullable(posReqVO.getAccount1000Value()).orElse("0");
---------------------------------------------------------------------------------------------------------------------------------------------------------
3.这是一种常见的 JSON 解析操作,它会尝试获取指定字段的值,如果该字段不存在或为 null,则返回空字符串 ""。
JSONObject jsonObject = customer.optJSONObject("Segments");
String segmentNo = json.optString("SegmentNo")
String partnerFlag = customerJson.opt("PartnerFlag");
4. jdk9及其以上:ifPresentOrElse() 的新方法。没有用jdk9,但是jdk8这样也能实现:
Optional.ofNullable(memberSegment)
.map(existingSegment -> {
CustomerLoyMemberSegmentPO updateSegmentPO = initMemberSegmentPO(memberCard, partnerCardDefnPO)
.setEndDate(null).setLastUpdated(DateUtils.utcNow());
memberSegmentRepository.updateSegmentByIdAndSegNum(updateSegmentPO);
return existingSegment;
})
.orElseGet(() -> {
memberSegmentRepository.insert(memberSegmentPO);
return null;
});
---------------------------------------------------------------------------------------------------------------------------------------------------------
5. 优化 if else,不想用if else,也可以考虑用函数式断言Predicate或BiPredicate 校验。
1:用三元运算和 Consumer 改造:
Consumer<List<CustomerLoyOrderTxnPO>> insertOperation = posConfirmPointVO.getIsRepeatedOrderFlag() ?
orderTxnRepository::signleInsertLoyCustomerTxnOrder :
orderTxnRepository::batchInsertLoyCustomerTxnOrder;
insertOperation.accept(orderTxnsList);
2:使用三元运算符,最简单实现。
now: memberVO.setStatus(StringUtils.isBlank(data.getStatus()) ? "In Progress" : data.getSubStatus());
to: memberVO.setStatus(Optional.ofNullable(data.getStatus()).orElse("In Progress"));
to: memberVO.setStatus(StringUtils.defaultString(data.getSubStatus(), "In Progress"));
3:用Predicate检验改造:
// 判断是否重复订单的条件
Predicate<PosConfirmPointVO> isRepeatedOrder = PosConfirmPointVO::getIsRepeatedOrderFlag;
// 定义处理重复订单的逻辑
Runnable handleRepeatedOrder = () -> checkInsertCustomerBueventTxn(bueventTxnPO, account, buEventAccountDefnXmPOS);
// 定义处理非重复订单的逻辑
Runnable handleNonRepeatedOrder = () -> {
customerBueventTxnRepository.insertCustomerBueventTxn(bueventTxnPO);
upsertBueventAccountByType(memberId, eventId, account, buEventAccountDefnXmPOS);
};
// 根据订单是否重复执行不同的逻辑,不想用if(isRepeatedOrder.test(posConfirmPointVO)){}
Optional.of(posConfirmPointVO)
.filter(isRepeatedOrder)
.ifPresentOrElse(
result -> handleRepeatedOrder.run(),
() -> handleNonRepeatedOrder.run()
);
4. 旧代码:
List<Account> accounts = posConfirmReqVO.getAccounts();
if (accounts.isEmpty()) {
return;
}
accounts.stream()
.filter(acc -> "1000".equals(acc.getId()))
.findFirst()
.ifPresent(x -> posConfirmReqVO.setAccount1000Value(x.getEarnValue()));
这样更好:
Optional.ofNullable(posConfirmReqVO.getAccounts())
.filter(accounts -> !accounts.isEmpty())
.flatMap(accounts -> accounts.stream()
.filter(acc -> "1000".equals(acc.getId()))
.findFirst())
.ifPresent(x -> posConfirmReqVO.setAccount1000Value(x.getEarnValue()));
--------------------------------------------------------------------------------------------------------------------------------------------------------
学海无涯 代码作伴