如何让代码看起来高大上(二)

背景

不同发展阶段的公司对代码质量的要求有所不同,往往在公司逐步走向壮大之后,技术中心越来越内卷,这就要求程序员不断完善代码,使其变得更灵活、更抽象!
实际情况是:程序员之间相互攀比,谁的代码越吊、越暗含一些所谓的思想;坐卧键盘间,笑谈天下事

老代码

程序中有一段老代码,更新or新增站点的票价;以这段代码为例,本文主要讲述在如何在代码细节上显得高大上。

 @Override
    public void searchAndInsert(FareDispatchDto dto) throws AppRunTimeException {
		if(null != dto){
		  List<DispatchDtoLs> disLs = dispatchService.findVehicleTypeDis(dto.getLineCode(),dto.getVehicleTypeCode());
          if(disLs!=null && disLs.size()>0){
            for(DispatchDtoLs dispatch : disLs){
                //查询站点是否有票价,首先要存在调度票价记录
                List<BusiDispatchPriceEx> priceLs = priceExMapper.findDisPrice(dispatch.getDispatchCode());
                if(priceLs !=null && priceLs.size() >0 ){
                    String soft = priceLs.get(0).getSoft();
                    boolean result = true;
                    for(BusiDispatchPriceEx price : priceLs){
                        if(price.getStationCode().equals(dto.getStationCode())){
                            if(price.getFullPrice() == null || price.getFullPrice().compareTo(BigDecimal.ZERO) == 0){
                                price.setFullPrice(dto.getTotalFee());
                                price.setHalfPrice(dto.getHalfFee());
                                price.setStationFullPrice(dto.getStationServiceFee());
                                price.setStationHalfPrice(dto.getHalfStationServiceFee());
                                price.setSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
                                price.setNetSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
                                logger.info("======searchAndInsert======"+price.toString());
                                priceExMapper.updateFarePrice(price);

                            }
                            result = false;break;
                        }
                    }
                    if(result){
                        BusiDispatchPriceDto  price = getPriceDto(dispatch,dto,soft);
                        price.setStationId(dto.getStationId());
                        saveWithDispatchCode(price,dispatch.getDispatchCode());
                    }
                }
            }

          }
		}
        
    }

以上代码,可读性是非常差的!而且对于很多有“品味”、有“逼格”的程序员大佬来说,看着这段代码如鲠在喉,眼睛刺痛,呼吸困难。他们不可避免的向你抛来“轻视、厌恶”的表情!如果不利用设计模式,就简单的写代码而言,如何在细节上“装的高大上”呢?

代码优化

本文只讲述代码优化细节,不去考虑设计模式,不做过多的设计!大佬们勿喷!代码优化如下:

 @Override
    public void searchAndInsert(FareDispatchDto dto) throws AppRunTimeException {
        if(Objects.isNull(dto)){
            return ;
        }
        List<DispatchDtoLs> disLs = dispatchService.findVehicleTypeDis(dto.getLineCode(),dto.getVehicleTypeCode());
        if(CollectionUtils.isEmpty(disLs)){
            return ;
        }
        for(DispatchDtoLs dispatch : disLs){
            //查询站点是否有票价,首先要存在调度票价记录
            List<BusiDispatchPriceEx> priceLs = priceExMapper.findDisPrice(dispatch.getDispatchCode());
            if(CollectionUtils.isEmpty(priceLs)){
                continue;
            }
            //如果数据库不存在站点票价,则新增站点票价
            boolean result = priceLs.stream().anyMatch(p -> dto.getStationCode().equals(p.getStationCode()));
            if(!result){
                savePriceByStation(dto, dispatch, priceLs);
            }
            priceLs.forEach(item ->{
                if(isUpdateFlag(dto, item)){
                    setPriceInfo(item,dto);
                    logger.info("DispatchPriceServiceImpl.updatePriceDto{}",item.toString());
                    priceExMapper.updateFarePrice(item);
                }
            });
        }
    }

    /**
     * 更否更新站点票价的标识判断
     * */
    private static boolean isUpdateFlag(FareDispatchDto dto, BusiDispatchPriceEx item) {
        return item.getStationCode().equals(dto.getStationCode()) && (item.getFullPrice() == null || item.getFullPrice().compareTo(BigDecimal.ZERO) == 0);
    }

    /**
     * 保存站点票价方法
     * */
    private void savePriceByStation(FareDispatchDto dto, DispatchDtoLs dispatch, List<BusiDispatchPriceEx> priceLs) {
        //底层代码已经对 soft 未空值情况做了处理
        String soft = "";
        Optional<BusiDispatchPriceEx> firstPrice = priceLs.stream().findFirst();
        if(firstPrice.isPresent()){
            soft = firstPrice.get().getSoft();
        }
        BusiDispatchPriceDto  price = getPriceDto(dispatch, dto,soft);
        price.setStationId(dto.getStationId());
        saveWithDispatchCode(price, dispatch.getDispatchCode());
    }

    private void setPriceInfo(BusiDispatchPriceEx price, FareDispatchDto dto) {
        price.setFullPrice(dto.getTotalFee());
        price.setHalfPrice(dto.getHalfFee());
        price.setStationFullPrice(dto.getStationServiceFee());
        price.setStationHalfPrice(dto.getHalfStationServiceFee());
        price.setSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
        price.setNetSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
    }

一、高大上1

if(null != dto){
}

优化为

if(Objects.isNull(dto)){
    return ;
 }

弃用 null 的判断,采用 Objects.isNull,同时不要用花括号去包整个方法,不符合条件,直接return;
实际上:入参校验应该向上抽象,利用@Validated框架等!当我没说!

二、高大上2

if(disLs!=null && disLs.size()>0){
}

优化为

if(CollectionUtils.isEmpty(disLs)){
  return ;
}

弃用对list 的原生判断,采用 CollectionUtils,同时不要用花括号去包整个方法,不符合条件,直接return;
实际上:这里还能使用 Optional.ofNullable!当我没说!

三、高大上3

boolean result = true;
for(BusiDispatchPriceEx price : priceLs){
     if(price.getStationCode().equals(dto.getStationCode())){
         result = false;break;
      }
   }
   if(result){
        saveWithDispatchCode(price,dispatch.getDispatchCode());
    }
}    

优化为

//如果数据库不存在站点票价,则新增站点票价
boolean result = priceLs.stream().anyMatch(p -> dto.getStationCode().equals(p.getStationCode()));
 if(!result){
     savePriceByStation(dto, dispatch, priceLs);
 }

弃用for循环去判断是否存在站点票价,而是直接改为Lambda 表达式,priceLs.stream().anyMatch(),代码直观,充满逼格!

四、高大上4

for(BusiDispatchPriceEx price : priceLs){
     if(price.getStationCode().equals(dto.getStationCode())){
          if(price.getFullPrice() == null || price.getFullPrice().compareTo(BigDecimal.ZERO) == 0){
                price.setFullPrice(dto.getTotalFee());
                price.setHalfPrice(dto.getHalfFee());
                price.setStationFullPrice(dto.getStationServiceFee());
                price.setStationHalfPrice(dto.getHalfStationServiceFee());
                price.setSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
                price.setNetSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
                logger.info("======searchAndInsert======"+price.toString());
                priceExMapper.updateFarePrice(price);
                }
              result = false;break;
       }
}  

优化为

priceLs.forEach(item ->{
     if(isUpdateFlag(dto, item)){
        setPriceInfo(item,dto);
        logger.info("DispatchPriceServiceImpl.updatePriceDto{}",item.toString());
        priceExMapper.updateFarePrice(item);
        }
});
 /**
  * 更否更新站点票价的标识判断
 * */
 private static boolean isUpdateFlag(FareDispatchDto dto, BusiDispatchPriceEx item) {
        return item.getStationCode().equals(dto.getStationCode()) && (item.getFullPrice() == null || item.getFullPrice().compareTo(BigDecimal.ZERO) == 0);
 }

private void setPriceInfo(BusiDispatchPriceEx price, FareDispatchDto dto) {
        price.setFullPrice(dto.getTotalFee());
        price.setHalfPrice(dto.getHalfFee());
        price.setStationFullPrice(dto.getStationServiceFee());
        price.setStationHalfPrice(dto.getHalfStationServiceFee());
        price.setSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
        price.setNetSellState(DispatchConstant.DISPATCH_PRICE_NOSITE);
    }

1、弃用for循环去判断,而是直接改为Lambda 表达式
2、复杂的if判断抽离出来,独立方法
3、dto.set()方法抽离出来,独立方法
4、logger.info打印日志形式,采用{}

五、高大上5

String soft = priceLs.get(0).getSoft();

优化为

//底层代码已经对 soft 未空值情况做了处理
String soft = "";
Optional<BusiDispatchPriceEx> firstPrice = priceLs.stream().findFirst();
if(firstPrice.isPresent()){
   soft = firstPrice.get().getSoft();
}

增加逼格buff,使用stream().findFirst()

优点

1、增加代码的可读性,使得整个方法呈现一种线性可读;
2、方法单一职能原则,比如:判断条件的方法,只用来判断条件;
3、善用 java8 引入的Lambda 表达式,充满逼格;
4、方法域不要太大,不要用{}去包很多代码,要干脆,断舍离!

实际优点

1、代码评审时,面上有光!你相信光吗?
2、提交代码时很有信心,希望被人看到!
3、感觉自己是一个有思想有品味的程序员;
4、飒爽、孤傲的背影、用了海飞丝;

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值