java代码优化小技巧

发布时间 2024-01-02 14:21:18作者: 做时间的好朋友

1.参数校验放到开始

一般将使用的参数校验放到起始位置,不要因为之前用的三元运算符而隐藏

// 验证输入参数
if (StringUtils.isBlank(request.getAlarmObject()) || Objects.nonNull(request.getAlarmObjectPlatform())) {
    throw new IllegalArgumentException("报警对象和平台不能为空");
}

2.三元运算符合并为if-else看起来更简介

之前三元运算符

AppInfo appInfoData = appInfoList.size() == 0
                ? new AppInfo().setAppEnName(request.getAlarmObject()).setAppDeployPlatform(request.getAlarmObjectPlatform()).setCode("AppInfo-" + UUID.randomUUID())
                : appInfoList.stream().filter(appInfo -> appInfo.getAppEnName().equalsIgnoreCase(request.getAlarmObject()) && appInfo.getAppDeployPlatform() == request.getAlarmObjectPlatform() && StringUtils.isBlank(appInfo.getAppDeployPlatformGroup())).collect(Collectors.toList()).get(0);

优化后的代码if-else

AppInfo appInfoData;

// 判断是否需要创建新的AppInfo
if (appInfoList.isEmpty()) {
    appInfoData = new AppInfo()
            .setAppEnName(request.getAlarmObject())
            .setAppDeployPlatform(request.getAlarmObjectPlatform())
            .setCode("AppInfo-" + UUID.randomUUID());
} else {
    appInfoData = appInfoList.stream()
            .filter(appInfo -> appInfo.getAppEnName().equalsIgnoreCase(request.getAlarmObject())
                    && appInfo.getAppDeployPlatform().equals(request.getAlarmObjectPlatform())
                    && StringUtils.isBlank(appInfo.getAppDeployPlatformGroup()))
            .findFirst()
            .orElseThrow(() -> new IllegalStateException("找不到匹配的AppInfo"));
}

3.注释及空格

相关功能不同的以空格分隔,并加有注释

// 保存或更新AppInfo
appInfoDaoService.saveOrUpdate(appInfoData, new UpdateWrapper<AppInfo>().eq(AppInfo.CODE_COLUMN, appInfoData.getCode()));

// 维护relation
RelationResGroupAppInfo relation = new RelationResGroupAppInfo()
        .setAppInfoCode(appInfoData.getCode())
        .setResGroupCode(request.getDefinition());
relation.setCreateUser(request.getUpdateUser().getEnName());
relation.setUpdateUser(request.getUpdateUser().getEnName());

// 删除旧的关系
relationResGroupAppInfoMapper.delete(new QueryWrapper<RelationResGroupAppInfo>().eq(RelationResGroupAppInfo.RES_GROUP_CODE_COLUMN, request.getDefinition()));
// 插入新的关系
relationResGroupAppInfoMapper.insert(relation);

4.列表中只有一个元素的,

List<String> definitions = Collections.singletonList(request.getDefinition());

5.列表是否为空

if (definitions.isEmpty()) {
     appInfoData = new AppInfo()
    .setAppEnName(request.getAlarmObject())
    .setAppDeployPlatform(request.getAlarmObjectPlatform())
    .setCode("AppInfo-" + UUID.randomUUID());
}