JAVA如何避免过多if判断
一. if里简单赋值
用三元或者Optional.orElse
方法
//简化前
if(remark == null){
remark = "无";
}
//三元
remark = remark ==null? "无": remark;
//Optional
remark = Optional.ofNullable(remark).orElse("无");
二. if里执行简单代码
用Optional.filter.ifPresent
方法
//简化前
if(uid < 1000){
order.setRemark("压测订单"+uid);
}
//简化后
Optional.of(uid).filter(uid -> uid <1000).ifPresent(uid -> order.setRemark("压测订单"+uid));
三. if里抛出异常
用Assert断言(这里用Spring)和Optional
, 推荐使用Assert断言
//简化前
if(payAmount < 0){
throw new AppException("异常订单");
}
//简化后
Assert.isTrue(payAmount < 0,"异常订单");
Optional.of(payAmount).filter(e -> e > 0).orElseThrow(() -> new RuntimeException("error num"));
四. if里稍复杂赋值
用Optional.filter.map.ifPresent.orElse等组合使用
//简化前
AddressContact matchedAddress= null;
if(!CollectionUtils.isEmpty()){
for(AddressContact address: addresses){
if(contactId.equals(address.getContactId())){
matchedAddress = address;
receiverInfo = address.getReceiverInfo();
}
}
}
//简化后
Optional.ofNullable(addresses).filter(c -> !CollectionUtils.isEmpty(c))
.map(c -> c.stream().filter(e -> contactId.equals(e.getContactId())).findFirst())
.ifPresent(address -> {
matchedAddress = address;
receiverInfo = address.getReceiverInfo();
});
五. if分支逻辑太多
- 方法一: 利用多个if+return, 达到先初始的简化
(if+return很多目前没找到好的优化, 部分场景可以在调用方法判断不符合直接不调用, 不合理的if越在前面判断代价越小)
- 方法二: 转换成switch或Map
如果不同的if类似于同一个场景的不同的值的判断, 可以定义枚举用switch或Map(初始化时添加所有case)