簡體   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