滴水恩情 发表于 2024-5-19 13:59:59

平常开发的优化代码:

第一: 检验,报错直接抛出非常: 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的情况下执行的代码;
if (List.of("a", "a", "a").stream().<strong>allMatch</strong>(Objects::nonNull)) {
    System.out.println("3个对象都不为空");
}第四:其中有2个条件任一匹配到:
   if(Stream.of(InProgress, Queued).<strong>anyMatch</strong>(status -> Objects.equals(source.getStatusCd(), status))){ }

或者:if(Arrays.asList(dailyLimit, monthLimit).contains(type)){}

或者:StringUtils.<strong>equalsAny</strong>(a,b,c)//只要有一个不为空第五:假如为null值,但是要转换字段类型取值,都可以用这种方法:
CustomerLoyTxnStg loyTxnStg = new CustomerLoyTxnStg();
loyTxnStg.setOrigPoints(Optional.ofNullable(source.getOrigPoints()).map(BigDecimal::valueOf).orElse(null));<br>或者:<br>memTier.setSeqNum(Objects.<strong>requireNonNullElse</strong>(tier, Tier::new).getSeqNum());<br>或者:<br>String birthDay = StringUtils.<strong>defaultIfEmpty</strong>(contact.getCustomBirthdayDay(), "1");<br>或者: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;
            });<br>第八:优化 if else,不想用if else,也可以考虑用函数式断言Predicate或BiPredicate 校验。
1:用三元运算和 Consumer 改造:<em id="__mceDel">Consumer<List<CustomerLoyOrderTxnPO>> insertOperation = posConfirmPointVO.getIsRepeatedOrderFlag() ?
                        orderTxnRepository::signleInsertLoyCustomerTxnOrder :
                        orderTxnRepository::batchInsertLoyCustomerTxnOrder;
                insertOperation.accept(orderTxnsList);<br>
2:使用三元运算符,最简单实现。<br>
3:用Predicate检验改造:
      // 判断是否重复订单的条件
      Predicate<PosConfirmPointVO> isRepeatedOrder = PosConfirmPointVO::getIsRepeatedOrderFlag;
      // 定义处理重复订单的逻辑
      Runnable handleRepeatedOrder = () -> checkInsertCustomerBueventTxn(bueventTxnPO, account, buEventAccountDefnXmPOS);<br>
      // 定义处理非重复订单的逻辑
      Runnable handleNonRepeatedOrder = () -> {
            customerBueventTxnRepository.insertCustomerBueventTxn(bueventTxnPO);
            upsertBueventAccountByType(memberId, eventId, account, buEventAccountDefnXmPOS);
      };
      // 根据订单是否重复执行不同的逻辑
      if (isRepeatedOrder.test(posConfirmPointVO)) {
            handleRepeatedOrder.run();
      } else {
            handleNonRepeatedOrder.run();
      }</em>第九:用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()));
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 平常开发的优化代码: