繁体   English   中英

要进行空检查还是不进行空检查?

[英]To null check or not to do a null check?

这是Josh bloch(Linkedlist.java)编写的代码

 * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

在这里,我没有看到对集合c的任何null ptr检查。 相反,有效的Java非常注重参数验证,强调空指针检查。 If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception.

我需要知道我在想什么吗? 换句话说,为什么他不对addAll函数执行null检查?

因为Object[] a = c.toArray(); 如果c为null,无论如何都会抛出指定的异常。

Object[] a = c.toArray(); 显然会抛出NPE。 在这种情况下,我会做的是要么在开始时检查参数是否为null,然后返回false (这样就不会破坏运行时流程assertIsNotNull -C风格),或者在方法开始时使用assertIsNotNull ,并在javadoc中指定它(例如,“事物不能为null,哟”)。

但这就是我。 这就是为什么必须始终对API进行充分记录的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM