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

前端 未结 4 1972
悲哀的现实
悲哀的现实 2020-12-20 01:56

I often see code like this:

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

When one could simply do the check like this:

相关标签:
4条回答
  • 2020-12-20 02:07

    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

    0 讨论(0)
  • 2020-12-20 02:21

    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 ;)

    0 讨论(0)
  • 2020-12-20 02:28

    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.

    0 讨论(0)
  • 2020-12-20 02:29

    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.

    0 讨论(0)
提交回复
热议问题