Search code examples
javaspringsonarqubesonarqube-scanmutable

Java mutable object to causing nullpointer exception


I have the following DTO and I pass the objects to the ArrayLists to prevent objects to be changed and fix the SonarQube error as "Message: Store a copy of allergenInfoList", etc.

public MenuItemDTO(
        PropertiesDTO propertiesDto,
        List<ModifierDTO> modifierDtoList,
        List<AllergenInfo> allergenInfoList
) {
    this.uuid = propertiesDto.getUuid();
    this.modifierDtoList = new ArrayList<>(modifierDtoList);
    this.allergenInfoList = new ArrayList<>(allergenInfoList);
  }
}

However, this approach requires null check and it makes my code ugly as shown below:

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);
    }
}

So, is there any better approach to fix the problem without null check?


Solution

  • It may be better to implement a utility/helper method to handle null checks (either directly, using Objects::isNull or Optional) and return expected result:

    public class Util {
        public static List<?> copyOrNull(List<?> src) {
            return null == src ? src : new ArrayList<>(src);
        }
    
        public static List<?> copyOrEmpty(List<?> src) {
            return null == src ? Collections.emptyList() : new ArrayList<>(src);
        }
    }
    

    Then update the DTO code as needed:

    
    public MenuItemDTO(
            PropertiesDTO propertiesDto,
            List<ModifierDTO> modifierDtoList,
            List<AllergenInfo> allergenInfoList
    ) {
        this.uuid = propertiesDto.getUuid();
        this.modifierDtoList = Util.copyOrNull(modifierDtoList);
        this.allergenInfoList = Util.copyOrEmpty(allergenInfoList);
    }