Besi
Besi

Reputation: 22959

Objective-C: Why should one check for != nil

I often see code like this:

// Approach 1
if(data != nil){
    // Do this and that
}

When one could simply do the check like this:

// Approach 2
if(data){
    // Do this and that
}

To me the second approach seems to be much better since it is shorter and easier to read.

So why should one use the first approach at all?

Upvotes: 2

Views: 210

Answers (4)

jerrylroberts
jerrylroberts

Reputation: 3454

You forgot the 3rd approach, which I use alot:

if( !data ) {
    return;
}

Like everyone else has touched on, a lot of it is style... and a lot of it depends on what the compiler supports. Type safe languages like C# and Java make you do:

if( data == null ) {
    return;
}

The objective c compiler will allow this type of "syntax sugar" where others will not. My opinion is take advantage of whatever features the compiler offers, and try to make your code as readable as you can for the next guy ;)

Upvotes: 0

Tim Dean
Tim Dean

Reputation: 8292

Some languages like Java require the conditional within the parenthesis to be a boolean expression. In those languages, you have to spell things like you do in approach 1. If you find yourself jumping from language to language, then I find it easier to stick with that approach. You have one way that works relatively consistently in all languages.

The second approach is more compact and some find it easier to read. It is just as valid, and probably more commonly used by C/C++/Objective-C developers. If you work exclusively in these C-based languages, it probably is more appropriate for you to use. Even if you choose not to use approach 2 for C-based languages, get used to seeing it whenever you look at other people's code.

Upvotes: 1

GrandMarquis
GrandMarquis

Reputation: 1913

This is mostly a style preference, or some people does not know that it is possible to use first solution.

Moreover, they are languages like java where you can't write the second solution, You must write yourVar != null

Upvotes: 5

zaph
zaph

Reputation: 112873

It is all about coding preferences. Some might feel that the longer form is more clear as to intent, others that it is overly verbose.

Upvotes: 4

Related Questions