short-circuit at OR (java)

在設計台灣郵遞區號app時,遇到一個問題:

if( datasave_zip.arr_save != null || datasave_zip.arr_save.size() > 0 )
{
   Log.e(TAG, "bypass! zip array save != null.");
   return;
}
上面這段code 有沒有錯呢?
大家猜猜看....
..
沒錯,一執行就當機了.
 java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
        at com.mark.taiwanpostmailbox.zip.datasave_zip.parpare_zip_data(datasave_zip.java:58)


我一開始寫的時候,考慮到OR short-circuit.
所以當
 datasave_zip.arr_save = null 時, 理論上第一個條件成立, 就不會判斷到第二個條件才對??!!
???
所以問題到底在哪裡呢?
為甚麼會當機呢?

答案在這啦:

There is only one case of short-circuiting for each operator, and they are:

  • false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
  • true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there

所以說: || OR 只在true時才會short-circuit, 而在false時,不會short-circuit. .... 故上面的例子會判斷第二個條件,但arr_save==null.所以null.size()就當機了.

這一點OR short-circuit對程式設計師來說,很容易搞混,而且只在run-time才會發生, compiler 不會發現這錯誤.
很多程式設計師在寫code時會沒有發現這邏輯上的失誤.
這就是很多時候, android app常常當機的原因了...


ps: AND && 是 false時, short-circuit才會成立,相反 true時就不會short-circuit.

口訣就是諧音: OR two AND four. (OR比AND小, 2比4小)
(OR TRUE AND FALSE)
(OR 只在true成立 short-circuit, AND 只在false成立short-circuit )






留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

SMR疊瓦式hdd致命缺陷被解決????!!!

ios app 上架時app icon要注意事項

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

舊有app在Android 12 閃退問題& app Splash screens

google play 正式發布前測試報告...非常好用.

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

Google Play badge徽章產生器