Friday, December 9, 2011

Tip of the day - Compare syntax

A good practice when checking against null, nil or any value (such as an integer) is to use the following syntax:
if(nil == object)
This avoids the situation where, if one uses the single equals to (=) instead of the double equals to (==), a compiler error will be generated and no executable created. On the other hand, if the other (more commonly used) syntax such as the following is used, no compiler errors would be generated:
if(object == nil)
The above code would also run as expected. However, if I wrote
if(object = nil)
this would cause the object to be set to nil and could lead to mysterious behavior when the program runs. The code may not be as natural to read, but does help in avoiding the obvious pitfall.