Why use if (!str) when you can use if (str)


#1

On page 153 in an example provided to Reading files with NSString there’s logical not used with if construct:

if (!str) { NSLog(@"read failed: %@", [error localizedDescription]); } else { NSLog(@"resolv.conf looks like this: %@", str); }
Why do that when if construct works without logical not:

if (str) { NSLog(@"resolv.conf looks like this: %@", str); } else { NSLog(@"read failed: %@", [error localizedDescription]); }
Is this some kind of a semantic? Do I gain anything when I use the first example rather than the second one?


#2

They achieve the same thing; however, the former takes a pessimistic outlook while the latter an optimistic outlook.


#3

Yeah, I find the pessimistic outlook a better on. Down to personal preference, I guess. After this chapter all my if statements start with the pessimistic approach
.


#4

When choosing between if (value) or if (!value) it depends on your goals. One goal is to put the favoured result first (ie the most likely result) and handle the code that would operate the most often first. The downside of this is that the rare code is handled sometimes many lines of code after the decision. So sometimes it is nice to have the rare exclusion handled first and gotten rid of and then the remainder can focus on the code that is run most of the time.

I usually like to handle the most common code first, then handle error handling. Just to show a flow of how things ‘should’ go. Not always though… if after a 25 lines of code, I have one line of error handling, I may put it earlier, just to keep it in the section where the choice is actually made. (Or alternatively I could stuff the long 25 lines into a new function, and keep the whole thing in a few lines of code (choice, call function or handle error))