代码瘦身优化实践

640?wx_fmt=gif

史蒂夫.乔布斯说,”复杂的终极境界是简单“,同样的优雅的代码一定是精简明了,可读性好。

640?wx_fmt=png

使用LocalDate和LocalDateTime

 LocalDate精确到日期,LocalDateTime精确到时分秒。 优化前14行代码 

01try{
02SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
03SimpleDateFormat sdfMins = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
04Date now = new Date();
05String today = sdfDay.format(now);
06String waterStart = today + " 03:00:00";
07String waterEnd = today + " 04:00:00";
08
09Date waterStartTime = sdfMins.parse(waterStart);
10Date waterEndTime = sdfMins.parse(waterEnd);
11}catch (ParseException pe) {
12  return XX;
13}

优化后3行代码

1LocalDateTime now = LocalDateTime.now();
2LocalDateTime waterStart = LocalDateTime.of(now.getYear(), now.getMonth(),now.getDayOfMonth(),3,0);
3LocalDateTime waterEndTime =LocalDateTime.of(now.getYear(), now.getMonth(),now.getDayOfMonth(),4,0);

默认值使用Optional

优化前五行

1if (null == status) {
2   param.put("status"new ArrayList<String>());
3  else {
4    param.put("status", status);
5  }

优化后一行,使用JDK8的Optional

1Optional.ofNullable(status).orElse(new ArrayList<String>());

如果是字符串可以用

1StringUtils.defaultIfEmpty(status,"")

字符串累加

 字符串只要不在for循环里累加,可以直接用+号,因为编译成字节码后会变成StringBuilder,如果在for循环里面用+号会生成多个StringBuilder,所以在for循环里累加最好在循环外创建StringBuilder。 优化前五行 

1StringBuffer sblog = new StringBuffer();
2sblog.append("waterDriven|sellerId=");
3sblog.append(request.getSellerTaobaoId());
4sblog.append("|result=");
5sblog.append(isSuccess);

 优化后一行 

1String sblog="waterDriven|sellerId="+request.getSellerTaobaoId()+"|result="+isSuccess;

 以上场景用逗号和等号连接数据,使用GUAVA的Joiner更精简,可读性更好 

1String sblog=Joiner.on("|").withKeyValueSeparator("=")
2                .join(ImmutableMap.of("sellerId", request.getSellerTaobaoId(), "result", isSuccess))

LIST TO MAP

 优化前4行 

1Map<String, String> AssetsMetaIdMap = Maps.newHashMap();
2        for (AssetsInfoBO assetsInfoBO : request.getAssetsCollectionList()) {
3           AssetsMetaIdMap.put(assetsInfoBO.getAssetMetadataId(), assetsInfoBO.getAssetMetadataId());
4        }

 优化后1行 

1Map<String, String> AssetsMetaIdMap = request.getAssetsCollectionList().stream().collect(Collectors.toMap(Hosting::getAssetMetadataId, Hosting::getAssetMetadataId));

 如果key重复会抛出异常

1Exception in thread "main" java.lang.IllegalStateException: Duplicate key 80000

减少不需要的判断

 优化前5行 

1String requestId = null;
2if (null != request.getExtData()) {
3    requestId = request.getExtDataValue(REQUEST_ID_KEY);
4}
5return requestId;

优化后1行

1return request.getExtDataValue(REQUEST_ID_KEY);

去掉else

 优化前5行 

1if (null != result &amp;&amp; StringUtils.isNotBlank(no)) {
2     return no;
3 } else {
4 throw new RuntimeException("XX");
5 }

 优化后4行 

1if (null != result &amp;&amp; StringUtils.isNotBlank(no)) {
2     return no;
3 }
4 throw new RuntimeException("XX");

不要返回布尔

 优化前5行 

1if ("true".equalsIgnoreCase(value.toString())) {
2    invoke = true;
3 else {
4    invoke = false;
5 }

 优化后一行 

1invoke = "true".equalsIgnoreCase(value.toString());

使用级联

优化前5行 

1ParamBO paramBO = new ParamBO();
2paramBO.setId(1);
3paramBO.setName(”ifeve“);
4paramBO.setOld(7);

优化后1行

view sourceprint?

1new ParamBO().withId(1).withName("ifeve").withOld(7);

(全文完)

点击下方
阅读原文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值