发送DTO时如何避免NULL?

时间:2017-12-02 17:42:25

标签: java spring hibernate spring-mvc spring-boot

我有一个包含多个列表的DTO

@Data
public class ContributionUpdate<T extends MovieRequest> {
    private Map<Long, T> elementsToAdd;
    private List<T> newElementsToAdd;
    private Map<Long, T> elementsToUpdate;
    private List<Long> idsToDelete;
}

发送对象时,某些课程可能为NULL。在这些列表上运行的方法看起来很糟糕,因为条件检查消息是否为NULL。 https://pastebin.com/niMiYzeg如果对象具有NULL列表,是否有任何正确的方法可以创建空列表?

4 个答案:

答案 0 :(得分:0)

可能是Apache CollectionsUtils方法emptyIfNull会帮助您:

public static <T> Collection<T> emptyIfNull(Collection<T> collection)
  

如果参数为null,则返回不可变的空集合   否则就是论证。

答案 1 :(得分:0)

您可以将DTO更新为:

@Data
public class ContributionUpdate<T extends MovieRequest> {
    private Map<Long, T> elementsToAdd = new HashMap<>();
    private List<T> newElementsToAdd = new ArrayList<>();
    private Map<Long, T> elementsToUpdate = new HashMap<>();
    private List<Long> idsToDelete = new ArrayList<>();
}

但它可能不是一个好的解决方案,您可以更好地更新您的服务,该服务会在没有数据的情况下返回此数据以返回空的地图或列表。

答案 2 :(得分:0)

Java中的引用类型总是不可为空,因此为了减少对空值的膨胀检查,可以强制使用assert语句使输入有效。

然后您的功能将从

开始
assert contribution.getElementsToAdd() != null;
assert contribution.getElementsToUpdate() != null;
assert contribution.contribution.getIdsToDelete() != null;
...

然后您可以安全地使用这些功能,并确保您拥有有效值。对于处理开发和测试的用户来说,断言将失败,这会使您的函数失效。

在某个时刻,它在防御性编码与某些点之间保持平衡,你说“看,如果你给我无效的输入,我只是要抛出异常&#34” ;

对于您的ContributionUpdate课程,您可以在构造函数中使用空值初始化每个地图/列表,这样您就不会默认为null引用并点击这些断言。< / p>

答案 3 :(得分:0)

  1. 列出最终列表和地图
  2. 在构造函数中设置它们(当然)。
  3. 使用setter设置值。
  4.      public void setBlammyList(final List newValue)
         {
            blammyList.clear();
    
            if (CollectionUtils.isNotEmpty(newValue))
            {
                blammyList.addAll(newValue);
            }
         }