I have the following DTO:
@Data
@RequiredArgsConstructor
public class MenuItemExpandedDTO {
private UUID uuid;
private List<ModifierGroupDTO> modifierGroupDtoList;
private List<AllergenInfo> allergenInfoList;
public MenuItemExpandedDTO(
PropertiesDTO propertiesDto,
List<ModifierGroupDTO> modifierGroupDtoList,
List<AllergenInfo> allergenInfoList
) {
this.uuid = propertiesDto.getUuid();
this.modifierGroupDtoList = modifierGroupDtoList;
this.allergenInfoList = allergenInfoList;
}
}
In SonarQube analysis, I get a Vulnerability due to allergenInfoList as it is stated
"Message: Store a copy of allergenInfoList"
So, I am not sure what the problem is, but before fixing this error, I am wondering what is wrong with that code? In some pages, it is recommended to initialize the list e.g. private List<AllergenInfo> allergenInfoList = Collections.emptyList(). But it is not a way I follow in my projects. So, what is the problem with this code?
SonarQube is telling you to be cautious when receiving
Lists in a constructor. Why? Because the caller holds a reference to thatListand it can do the following with it if it is not immutable:Listcontent by adding or removing elements to it, actually affecting yourMenuItemExpandedDTO.Listif they are not immutable. This means thatAllergenInfoobjects in theListcan be changed affecting yourMenuItemExpandedDTOobject.To tackle 1., you can simply store a copy of the
Listas SonarQube suggests:Tackling 2. is trickier and the simplest and more reliable solution is to use immutable objects. You can read more about this and how to design your classes so that you have immutable objects at https://www.baeldung.com/java-immutable-object.
Keep in mind that
ModifierGroupDTOandAllergenInfomust also be immutable so thatMenuItemExpandedDTOis 100% immutable.