代码瘦身优化实践

使用LocalDate和LocalDateTime

Before

try{
    SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdfMins = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date now = new Date();
    String today = sdfDay.format(now);
    String waterStart = today + " 03:00:00";
    String waterEnd = today + " 04:00:00";

    Date waterStartTime = sdfMins.parse(waterStart);
    Date waterEndTime = sdfMins.parse(waterEnd);
}catch (Exception e){

}

After

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

使用LocalDate精确到日期,LocalDateTime精确到时分秒

默认值使用Optional

Before

String state = null;
if (null == status) {
    state = "A";
}else {
    state = status;
}

After

String state = Optional.ofNullable(status).orElse("A");
// Integer state = Optional.ofNullable(status).orElse(0);
// OR
String state = StringUtils.defaultIfEmpty(status, "A");

字符串累加

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

Before

StringBuffer sblog = new StringBuffer();
sblog.append("waterDriven|sellerId=");
sblog.append(request.getSellerTaobaoId());
sblog.append("|result=");
sblog.append(isSuccess);

After

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

对于用逗号和等号连接的数据,使用GUAVA的Joiner更精简,可读性更好

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

List To Map

Before

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

After

如果使用Stream的处理,出现key相同时会抛出异常

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

尝试使用级联

Before

ParamBO paramBO = new ParamBO();
paramBO.setId(1);
paramBO.setName("ifeve");
paramBO.setOId(7);

After

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