代码瘦身优化实践

代码瘦身优化实践

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

代码瘦身优化实践

使用LocalDate和LocalDateTime

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

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

优化后3行代码

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

默认值使用Optional

优化前五行

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

优化后一行,使用JDK8的Optional

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

如果是字符串可以用

1 StringUtils.defaultIfEmpty(status,"")

字符串累加

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

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

 优化后一行 

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

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

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

LIST TO MAP

 优化前4行 

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

 优化后1行 

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

 如果key重复会抛出异常

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

减少不需要的判断

 优化前5行 

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

优化后1行

1 return request.getExtDataValue(REQUEST_ID_KEY);

去掉else

 优化前5行 

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

 优化后4行 

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

不要返回布尔

 优化前5行 

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

 优化后一行 

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

使用级联

优化前5行 

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

优化后1行

view sourceprint?

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

(全文完)

点击下方
阅读原文