On a similar note of the Yoda conditions, also the nil check has been at the centre of debates. Some notous libraries out there use to check for an object to be or not to be nil as so:
【疑問】類似于 Yoda 表達式,nil 檢查的方式也是存在爭議的。一些 notous 庫 像這樣檢查對象是否為 nil:
~~~
if (nil == myValue) { ...
~~~
或許有人會提出這是錯的,因為在 nil 作為一個常量的情況下,這樣做就像 Yoda 表達式了。 但是一些程序員這么做的原因是為了避免調試的困難,看下面的代碼:
~~~
if (myValue == nil) { ...
~~~
如果程序員敲錯成這樣:
~~~
if (myValue = nil) { ...
~~~
這是合法的語句,但是即使你是一個豐富經驗的程序員,即使盯著眼睛瞧上好多遍也很難調試出錯誤。但是如果把 nil 放在左邊,因為它不能被賦值,所以就不會發生這樣的錯誤。 如果程序員這樣做,他/她就可以輕松檢查出可能的原因,比一遍一遍查看敲下的代碼要好很多。
為了避免這些奇怪的問題,途徑是使用感嘆號來判斷。因為 nil 是 解釋到 NO 所以沒必要在條件語句里面把它和其他值比較。同時,不要直接把它和 `YES` 比較,因為 `YES` 的定義是 1 而 `BOOL` 是 8 位的,實際上是 char 類型。
**推薦:**
~~~
if (someObject) { ...
if (![someObject boolValue]) { ...
if (!someObject) { ...
~~~
**不推薦:**
~~~
if (someObject == YES) { ... // Wrong
if (myRawValue == YES) { ... // Never do this.
if ([someObject boolValue] == NO) { ...
~~~
這樣同時也能提高一致性,以及提升可讀性。