【发布时间】:2021-11-25 11:09:50
【问题描述】:
我有以下 DTO,我将对象传递给 ArrayLists 以防止更改对象并将 SonarQube 错误修复为 “消息:存储 allergenInfoList 的副本” 等。
public MenuItemDTO(
PropertiesDTO propertiesDto,
List<ModifierDTO> modifierDtoList,
List<AllergenInfo> allergenInfoList
) {
this.uuid = propertiesDto.getUuid();
this.modifierDtoList = new ArrayList<>(modifierDtoList);
this.allergenInfoList = new ArrayList<>(allergenInfoList);
}
}
但是,这种方法需要空检查,它使我的代码丑陋,如下所示:
public MenuItemDTO(
PropertiesDTO propertiesDto,
List<ModifierDTO> modifierDtoList,
List<AllergenInfo> allergenInfoList
) {
this.uuid = propertiesDto.getUuid();
if (modifierDtoList != null) {
this.modifierDtoList = new ArrayList<>(modifierDtoList);
}
if (allergenInfoList != null) {
this.allergenInfoList = new ArrayList<>(allergenInfoList);
}
}
那么,有没有更好的方法来解决没有空检查的问题?
【问题讨论】:
-
在调用构造函数之前,可以检查它们是否不为空。但这很好。它不必总是美丽的。
标签: java spring sonarqube sonarqube-scan mutable