6

Most of the assertions I write are based on a conditional expression, like so:

  • NSParameterAssert(key != nil);
  • NSAssert(count <= MAX_FACTOR_COUNT, @"Too many factors");
  • NSAssert1(size % 2 == 1, @"Cannot create hexagonal board with even size %i", size);

But I also have quite a few cases of triggering an assertion failure with a hard-coded false value:

  • NSAssert(false, @"Abstract method invoked");
  • NSAssert(false, @"Unimplemented");
  • NSAssert(false, @"Invalid operation for this subclass");

This feels wrong to me. I feel like I should be saying something like this instead:

  • NSAssertFail(@"Abstract method invoked");
  • NSAssertFail(@"Unimplemented");
  • NSAssertFail(@"Invalid operation for this subclass");

My question is: How have people traditionally dealt with this? What do you name a preprocessor macro that wraps NSAssert(false, ...)?

Is NSAssertFail() a good name?

Todd Lehman
  • 2,880
  • 1
  • 26
  • 32
  • 1
    Just `#define NSAssertFail(x) do { NSAssert(0, x); } while(0)` – CodaFi Jul 05 '13 at 03:56
  • 1
    I was thinking just `#define NSAssertFail(x) NSAssert(0,x)`. What magic does the `do`...`while(0)` add? – Todd Lehman Jul 05 '13 at 04:09
  • 1
    It creates an inner scope. It's a good idea to do it for any macros that call methods, especially with arguments, and usually gets optimized away. – CodaFi Jul 05 '13 at 04:10
  • Ok, I can see that helping with certain types of macros. Does it make a difference in this case? Just wanna make sure I'm not missing something. A related question: how is `do { foo(...); } while(0)` different from `{ foo(...); }`? – Todd Lehman Jul 05 '13 at 04:12
  • 1
    Here, this is a better explanation than I could ever give: http://stackoverflow.com/questions/1067226/c-multi-line-macro-do-while0-vs-scope-block – CodaFi Jul 05 '13 at 04:15
  • 1
    @CodeFi but the `NSAssert` macro is already wrapped in one. – Cole Tobin Jul 05 '13 at 04:23
  • @ColeJohnson I still do it (mostly out of habit). And it's not like `do { do { NSAssert(0, x); } while(0); } while(0);` does anything exceptionally weird. – CodaFi Jul 05 '13 at 04:36
  • @CodaFi you never know! It could loop out of fear the programmer is incompetent. (The code sucks and it doesn't want to run it anymore, so it give up and loops) – Cole Tobin Jul 05 '13 at 04:37
  • @ColeJohnson We have standards bodies that prevent that kind of thing from happening. C isn't Java. – CodaFi Jul 05 '13 at 04:46
  • @CodaFi they aren't required completely in a sense. GCC claims C++11 support just because some of it is. – Cole Tobin Jul 05 '13 at 05:33

0 Answers0