平时开发的优化代码:

· 浏览次数 : 0

小编点评

The provided content covers various aspects of checking for null values and handling different scenarios: **1. Checking for null:** * `Objects.requireNonNull(contactId)` throws an `IllegalArgumentException` if `contactId` is null. * `List.of("a", "a", "a").stream().allMatch(Objects::nonNull)` checks if all elements in the list are not null. **2. Handling multiple conditions:** * `if(Stream.of(InProgress, Queued).anyMatch(status -> Objects.equals(source.getStatusCd(), status))}` checks if the order is in either "InProgress" or "Queued" status. * `if(Arrays.asList(dailyLimit, monthLimit).contains(type)){}` checks if the specified type is within the allowed range. **3. Handling null values:** * `Optional.ofNullable(source.getOrigPoints()).map(BigDecimal::valueOf).orElse(null)` handles null values by converting them to a `BigDecimal` object. * `memTier.setSeqNum(Objects.requireNonNullElse(tier, Tier::new).getSeqNum());` sets the `seqNum` field to the default value if it's null. **4. JSON parsing:** * `String segmentNo = json.optString("SegmentNo")` retrieves the `SegmentNo` from the JSON string. * `String partnerFlag = customerJson.opt("PartnerFlag")` retrieves the `PartnerFlag` from the JSON object. **5. Conditional logic:** * `Optional.ofNullable(memberSegment) .map(existingSegment -> {...}` checks if a member segment already exists and updates it if it does. * `if (isRepeatedOrder.test(posConfirmPointVO)) { handleRepeatedOrder.run(); } else { handleNonRepeatedOrder.run(); }` executes different logic based on whether the order is repeated. **6. Stream operations for handling nulls:** * `Stream.of(apolloServiceConfig.parseItemUrl(), isUpdateBlue ? apolloServiceConfig.parseBlueItemUrl() : Stream.empty())` loads configuration URLs based on the `isUpdateBlue` flag. **7. Stream lambda expression:** * `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()))` updates the `account1000` value with the first non-empty account's earning. **8. Optimizing conditional checks:** * The new code uses an `if`-`else` block for improved readability and avoids the need for separate `if` conditions. **9. Jdk9 optimization:** * The code uses lambda expressions and `Stream` operations for improved readability and performance. **10. Stream optimization:** * The new code uses `Optional` to handle null values and returns the relevant object or a default value.

正文

第一: 检验,报错直接抛出异常: 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().allMatch(Objects::nonNull)) {
    System.out.println("3个对象都不为空");
}

第四:其中有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); }; // 根据订单是否重复执行不同的逻辑 if (isRepeatedOrder.test(posConfirmPointVO)) { handleRepeatedOrder.run(); } else { 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()));

与平时开发的优化代码:相似的内容:

平时开发的优化代码:

第一: 检验,报错直接抛出异常: Objects.requireNonNull(contactId); 第二:方法名,检查是否需要输出日志: if(printLogIfNeeded) //对于sql查询方法、java中的方法名字的命名定义推荐: find..By/query..By/get..By

《优化接口设计的思路》系列:第一篇—接口参数的一些弯弯绕绕

前言 大家好!我是sum墨,一个一线的底层码农,平时喜欢研究和思考一些技术相关的问题并整理成文,限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。 作为一名从业已达六年的老码农,我的工作主要是开发后端Java业务系统,包括各种管理后台和小程序等。在这些项目中,我设计过单/多租户体系系统,对接

《优化接口设计的思路》系列:第二篇—接口用户上下文的设计与实现

前言 大家好!我是sum墨,一个一线的底层码农,平时喜欢研究和思考一些技术相关的问题并整理成文,限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。 作为一名从业已达六年的老码农,我的工作主要是开发后端Java业务系统,包括各种管理后台和小程序等。在这些项目中,我设计过单/多租户体系系统,对接

《优化接口设计的思路》系列:第三篇—留下用户调用接口的痕迹

前言 大家好!我是sum墨,一个一线的底层码农,平时喜欢研究和思考一些技术相关的问题并整理成文,限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。 作为一名从业已达六年的老码农,我的工作主要是开发后端Java业务系统,包括各种管理后台和小程序等。在这些项目中,我设计过单/多租户体系系统,对接

《优化接口设计的思路》系列:第四篇—接口的权限控制

前言 大家好!我是sum墨,一个一线的底层码农,平时喜欢研究和思考一些技术相关的问题并整理成文,限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。 作为一名从业已达六年的老码农,我的工作主要是开发后端Java业务系统,包括各种管理后台和小程序等。在这些项目中,我设计过单/多租户体系系统,对接

《优化接口设计的思路》系列:第十篇—网站的静态资源怎么获取?

一、前言 大家好!我是sum墨,一个一线的底层码农,平时喜欢研究和思考一些技术相关的问题并整理成文,限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。 作为一名从业已达六年的老码农,我的工作主要是开发后端Java业务系统,包括各种管理后台和小程序等。在这些项目中,我设计过单/多租户体系系统,

iOS气泡提示工具BubblePopup的使用

在平时的开发中,通常新手引导页或功能提示页会出现气泡弹窗来做提示。如果遇到了这类功能通常需要花费一定的精力来写这么一个工具的,这里写了一个气泡弹窗工具,希望能帮你提升一些开发效率。 使用方法 1.从gitHub上下载代码到本地,代码地址:https://github.com/zhfei/Bubble

iOS中容易用错的常用知识点

坐标系转换 ios中的坐标系有三种 视图坐标系:原点(0,0)视图的左上角 窗口坐标系:原点(0,0)窗口的左上角 世界坐标系:原点(0,0)游戏中世界的原点 平时开发中经常会遇到转UIWindow坐标问题,如:已知一个UI控件的坐标,把它转换到UIWindow时,它对应的UIWindow坐标是什么

浏览器DevTools使用技巧

我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品。我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值。 本文作者:正则 作为一名前端开发人员,平时开发中使用最多的就是 Chrome devtools,但可能很多同学像我一样平时用的最多也就 Console、Elements

屏幕图像渲染原理

对于一个客户端开发来说,平时做的的最多的就是写页面,所以有必要了解从视图代码到图像显示到屏幕上的整个过程和原理。 下面以从视图代码到显示器图像的中间产物帧缓冲区图像位图为目标,分析从视图代码到帧缓冲区位图和从帧缓冲区位图到显示器图像这2个过程。 这里把这2个过程命名为:帧缓冲区数据怎么来的、帧缓冲区