Is comparing a BOOL against YES dangerous?

后端 未结 4 2102
轻奢々
轻奢々 2020-12-15 12:29

I found a comment today in a source file:

//  - no longer compare BOOL against YES (dangerous!)

Is comparing BOOL against

4条回答
  •  心在旅途
    2020-12-15 12:59

    All this is true, but there are valid counter arguments that might be considered:

    — Maybe we want to check a BOOL is actually YES or NO. Really, storing any other value than 0 or 1 in a BOOL is pretty incorrect. If it happens, isn't it more likely because of a bug somewhere else in the codebase, and isn't not explicitly checking against YES just masking this bug? I think this is way more likely than a sloppy programmer using BOOL in a non-standard way. So, I think I'd want my tests to fail if my BOOL isn't YES when I'm looking for truth.

    — I don't necessarily agree that "if (isWhatever)" is more readable especially when evaluating long, but otherwise readable, function calls,

    e.g. compare

    if ([myObj doThisBigThingWithName:@"Name" andDate:[NSDate now]]) {}
    

    with:

    if (![myObj doThisBigThingWithName:@"Name" andDate:[NSDate now]]) {}
    

    The first is comparing against true, the second against false and it's hard to tell the difference when quickly reading code, right?

    Compare this to:

    if ([myObj doThisBigThingWithName:@"Name" andDate:[NSDate now]] == YES) {}
    

    and

    if ([myObj doThisBigThingWithName:@"Name" andDate:[NSDate now]] == NO) {}
    

    …and isn't it much more readable?

    Again, I'm not saying one way is correct and the other's wrong, but there are some counterpoints.

提交回复
热议问题