views:

120

answers:

2

I would lean towards

if (object == nil)

but I've noticed in some tutorials the use of

if (nil == object)

Is this just a style thing, or is there some justified rationale for using either format?

+2  A: 

The if (nil == object) version protects you better in case you accidentally put = instead of ==.

Jim
+10  A: 

This is typically done to prevent using an assignment operator instead of a comparison operator. If you accidently typed this for instance:

if (object = nil)

It may compile but it isn't what you intended.

By using the second form you will ensure a compile time error if you mistype it, as nil cant be used as the left operand in assignments.

Please note I'm not an objective C programmer, but this question is generic to a lot of languages.

Neil Aitken
OK. It seems to me though that if you have enough presence of mind to put the nil first (in case you type a single =), you've already reminded yourself to do the double ==. Thanks.
Bill
Indeed, I usually don't bother with the second form, but some people prefer it just to be safe, and prevent sometimes hard to find bugs.
Neil Aitken