平时开发的优化代码(工具类等):

第一: 检验,报错直接抛出异常: Objects.requireNonNull(contactId);

第二:方法名,检查是否需要输出日志: if(printLogIfNeeded)   //对于sql查询方法、java中的方法名字的命名定义推荐: find..By/query..By/get..By

// 业务检验需要返回的code,这里返回异常,用全局异常捕获再返回给前端
CustomerBuPO customerBu = Optional.ofNullable(foundationRepository.getBuByName(reqVO.getBuId()))
           .orElseThrow(() -> new BusinessException(101, "buId not exist"));

第三:三个字段都不为null的情况下执行的代码; 3个对象都匹配不到;

if (List.of("a", "b", "c").stream().allMatch(Objects::nonNull)) {
    System.out.println("3个对象都不为空");
}
/** 简化判断: 2个对象是否不等于4*/
if (Stream.of(1, 2).noneMatch(x -> x == 4)) {
    System.out.println("a=4");
}

/** 简化判断: a 对象既不等于 b 对象,也不等于 c 对象*/
if (Stream.of("b", "c").noneMatch("a"::equals)) {
    System.out.println("==a");
}

第四:其中有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)  //只要有一个不为空

第五:如果为null值,但是要转换字段类型取值,都可以用这种方法:

CustomerLoyTxnStg loyTxnStg = new CustomerLoyTxnStg();
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");
或者:

1. 判断为null给默认值:

String pointValue = posReqVO.getAccount1000Value() == null? "0":posReqVO.getAccount1000Value();
String pointValue = Optional.ofNullable(posReqVO.getAccount1000Value()).orElse("0");

第六:这是一种常见的 JSON 解析操作,它会尝试获取指定字段的值,如果该字段不存在或为 null,则返回空字符串 ""。

String segmentNo = json.optString("SegmentNo")
String partnerFlag = customerJson.opt("PartnerFlag");
JSONObject jsonObject = customer.optJSONObject("Segments");

第七: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;
            });

第八:优化 if else,不想用if else,也可以考虑用函数式断言Predicate或BiPredicate 校验。

1:用三元运算和 Consumer 改造:
Consumer<List<CustomerLoyOrderTxnPO>> insertOperation = posConfirmPointVO.getIsRepeatedOrderFlag() ?
                        orderTxnRepository::signleInsertLoyCustomerTxnOrder :
                        orderTxnRepository::batchInsertLoyCustomerTxnOrder;
                insertOperation.accept(orderTxnsList);

2:使用三元运算符,最简单实现。

3:用Predicate检验改造:
        // 判断是否重复订单的条件
        Predicate<PosConfirmPointVO> isRepeatedOrder = PosConfirmPointVO::getIsRepeatedOrderFlag;
        // 定义处理重复订单的逻辑
        Runnable handleRepeatedOrder = () -> checkInsertCustomerBueventTxn(bueventTxnPO, account, buEventAccountDefnXmPOS);

        // 定义处理非重复订单的逻辑
        Runnable handleNonRepeatedOrder = () -> {
            customerBueventTxnRepository.insertCustomerBueventTxn(bueventTxnPO);
            upsertBueventAccountByType(memberId, eventId, account, buEventAccountDefnXmPOS);
        };
        // 根据订单是否重复执行不同的逻辑1
        if (isRepeatedOrder.test(posConfirmPointVO)) {
            handleRepeatedOrder.run();
        } else {
            handleNonRepeatedOrder.run();
        }
        // 根据订单是否重复执行不同的逻辑2      
        Optional.of(posConfirmPointVO)
        .filter(isRepeatedOrder)
        .ifPresentOrElse(
            result -> handleRepeatedOrder.run(),
            () -> handleNonRepeatedOrder.run()
        );

第九:用jdk8 优化旧代码:

1. 旧代码:
    String authToken = getAuthToken();
    updateApolloConfig(count, authToken, apolloServiceConfig.parseItemUrl());

    if (isUpdateBlue) {
        updateApolloConfig(count, authToken, apolloServiceConfig.parseBlueItemUrl());
    }
 这样不更好:    
    Stream.of(apolloServiceConfig.parseItemUrl(),
                isUpdateBlue ? apolloServiceConfig.parseBlueItemUrl() : Stream.empty())
        .forEach(url -> updateApolloConfig(count, getAuthToken(), url)); 
        
2. 旧代码,包含判断数据不为空:
    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()));
posted @ 2024-05-09 15:00  威兰达  阅读(206)  评论(0编辑  收藏  举报