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)
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 befalse
regardless of the value theretrue || ...
- it is not necessary to know what the right-hand side is because the result can only betrue
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 )
留言
張貼留言